复制 Groovy 类属性 [英] Copy Groovy class properties
问题描述
我想以通用方式将对象属性复制到另一个对象(如果目标对象上存在属性,我从源对象复制它).
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屋!