Groovy - 将属性从一个对象绑定到另一个对象 [英] Groovy - bind properties from one object to another
本文介绍了Groovy - 将属性从一个对象绑定到另一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
assertone -foo== two.foo
assertone-bar== two.bar
assert!two.baz
结果是一个错误:无法设置只读属性:类的属性:两个
解决方案
<问题是,对于每个对象, .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')
//您可能需要定义一个辅助方法,该方法对于任何Groovy都执行以下3行对象
def propsMap = one.properties
propsMap.remove('metaClass')
propsMap.remove('class')
def two = new Two(propsMap )
assertone-foo== two.foo
assertone-bar== two.bar
assert!two.baz
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
The result is an error: Cannot set readonly property: properties for class: Two
解决方案
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屋!
查看全文