groovy使用属性更改bean变量
groovy中是否有一种方法可以执行以下操作:groovy使用属性更改bean变量,groovy,Groovy,groovy中是否有一种方法可以执行以下操作: class Person{ def name, surname } public void aMethod(anoherBean){ def bean = retrieveMyBean() p.properties = anoherBean.properties } 属性属性是最终属性,是否有其他方法可以实现此快捷方式?如果没有任何特殊原因,请使用命名参数 def p = new Person(name: 'John',
class Person{
def name, surname
}
public void aMethod(anoherBean){
def bean = retrieveMyBean()
p.properties = anoherBean.properties
}
属性属性是最终属性,是否有其他方法可以实现此快捷方式?如果没有任何特殊原因,请使用命名参数
def p = new Person(name: 'John', surname: 'Lennon')
问题更新后
static copyProperties(from, to) {
from.properties.each { key, value ->
if (to.hasProperty(key) && !(key in ['class', 'metaClass']))
to[key] = value
}
}
properties
是虚拟财产;你必须打电话给各个设定者。试试这个:
def values = [name: 'John', surname: 'Lennon']
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
或者,使用拖把:
Object.class.putAllProperties = { values ->
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
}
Person p = new Person();
p.putAllProperties [name: 'John', surname: 'Lennon']
[编辑]要实现您想要的功能,必须循环访问属性。描述如何执行此操作:
def copyProperties(def source, def target){
target.metaClass.properties.each{
if (source.metaClass.hasProperty(source, it.name) && it.name != 'metaClass' && it.name != 'class')
it.setProperty(target, source.metaClass.getProperty(source, it.name))
}
}
你为什么要这么做?有什么原因吗?因为我懒得写所有的set方法:P.不,说真的,这个对象是在应用程序的另一个点上创建的,我想设置所有的属性,如果我不知道对象的类型代码不完整,现在检查。我能做我想做的吗?