Groovy - 将属性从一个对象绑定到另一个对象 [英] Groovy - bind properties from one object to another
问题描述
有没有办法将一个类的一个实例的属性绑定到另一个类的一个实例的属性(两者之间的公共字段).请看下面的例子:
Is there a way to bind properties from one instance of a class to the properties of an instance of another class (the common fields between the two). See the example below:
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
结果报错:Cannot set readonly property: properties for class: Two
The result is an error: Cannot set readonly property: properties for class: Two
推荐答案
问题是对于每个对象,.properties
包括两个内置的 Groovy-defined 属性,它们是 metaClass
和 class
.您要做的只是设置用户定义 属性.您可以使用如下所示的代码轻松完成此操作:
The problem is that for every object, .properties
includes two built-in Groovy-defined properties, these are the metaClass
and class
. What you want to do is only set the user-defined properties. You can easily do this using code such as that shown below:
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
这篇关于Groovy - 将属性从一个对象绑定到另一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!