相关疑难解决方法(0)

复制Groovy类属性

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

我的代码使用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, …
Run Code Online (Sandbox Code Playgroud)

groovy properties class expandometaclass property-list

15
推荐指数
2
解决办法
2万
查看次数