【发布时间】:2012-02-22 17:52:54
【问题描述】:
我想以通用方式将对象属性复制到另一个对象(如果目标对象上存在属性,我会从源对象中复制它)。
我的代码使用ExpandoMetaClass 可以正常工作,但我不喜欢这个解决方案。还有其他方法可以做到这一点吗?
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
【问题讨论】:
-
您可以随时使用 BeanUtils。
-
@DaveNewton 不确定 BeanUtils 是否能正常工作,因为源和目标是不同的类...
-
使用 AutoClone 注释怎么样? groovy.codehaus.org/gapi/groovy/transform/AutoClone.html
标签: class groovy properties property-list expandometaclass