是否有办法将属性从一个类的实例绑定到另一个类的实例的属性(两者之间的公共字段)。请参阅以下示例:
class One {
String foo
String bar
}
class Two {
String foo
String bar
String baz
}
def one = new One(foo:'one-foo', bar:'one-bar')
def two = new Two()
two.properties = one.properties
assert "one-foo" == two.foo
assert "one-bar" == two.bar
assert !two.baz
结果是错误:无法设置readonly属性:类的属性:两个
答案 0 :(得分:9)
我会按照我的建议here选择 InvokerHelper.set属性。
use(InvokerHelper) {
two.setProperties(one.properties)
}
答案 1 :(得分:6)
问题在于,对于每个对象,.properties
都包含两个内置的 Groovy定义的属性,这些属性是metaClass
和class
。您要做的只是设置用户定义的属性。您可以使用如下所示的代码轻松完成此操作:
class One {
String foo
String bar
}
class Two {
String foo
String bar
String baz
}
def one = new One(foo:'one-foo', bar:'one-bar')
// You'll probably want to define a helper method that does the following 3 lines for any Groovy object
def propsMap = one.properties
propsMap.remove('metaClass')
propsMap.remove('class')
def two = new Two(propsMap)
assert "one-foo" == two.foo
assert "one-bar" == two.bar
assert !two.baz