复制Groovy类属性 [英] Copy Groovy class properties

查看:229
本文介绍了复制Groovy类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以通用方式将对象属性复制到另一个对象(如果目标对象上存在属性,则从源对象复制它)。

I want to copy object properties to another object in a generic way (if a property exists on target object, I copy it from the source object).

我的代码可以使用 ExpandoMetaClass 正常工作,但我不喜欢解。有没有其他方法来做到这一点?

My code works fine using ExpandoMetaClass, but I don't like the solution. Are there any other ways to do this?

class User {
    String name = 'Arturo'
    String city = 'Madrid'
    Integer age = 27
}

class AdminUser {
    String name
    String city
    Integer age
}

def copyProperties(source, target) {
    target.properties.each { key, value ->
        if (source.metaClass.hasProperty(source, key) && key != 'class' && key != 'metaClass') {
            target.setProperty(key, source.metaClass.getProperty(source, key))
        }
    }
}

def (user, adminUser) = [new User(), new AdminUser()]
assert adminUser.name == null
assert adminUser.city == null
assert adminUser.age == null

copyProperties(user, adminUser)
assert adminUser.name == 'Arturo'
assert adminUser.city == 'Madrid'
assert adminUser.age == 27


推荐答案

我认为你的解决方案是相当不错的,是在正确的轨道。至少我觉得这是很容易理解的。

I think your solution is quite good and is in the right track. At least I find it quite understandable.

该解决方案的更多版本可能是...

A more succint version of that solution could be...

def copyProperties(source, target) {
    source.properties.each { key, value ->
        if (target.hasProperty(key) && !(key in ['class', 'metaClass'])) 
            target[key] = value
    }
}

...但它并没有根本的不同。我迭代源属性,所以我可以使用值分配给目标:)。它可能不如你的原始解决方案健壮,因为我认为如果目标对象定义 getAt(String)方法会破坏。

... but it's not fundamentally different. I'm iterating over the source properties so I can then use the values to assign to the target :). It may be less robust than your original solution though, as I think it would break if the target object defines a getAt(String) method.

如果你想要想,你可以这样做:

If you want to get fancy, you might do something like this:

def copyProperties(source, target) {
    def (sProps, tProps) = [source, target]*.properties*.keySet()
    def commonProps = sProps.intersect(tProps) - ['class', 'metaClass']
    commonProps.each { target[it] = source[it] }
}

基本上,它首先计算两个对象之间的公共属性,然后复制它们。它也有效,但我认为第一个更简单,更容易理解:)

Basically, it first computes the common properties between the two objects and then copies them. It also works, but I think the first one is more straightforward and easier to understand :)

有时更少是更多。

这篇关于复制Groovy类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆