有没有办法将属性从一个类的实例绑定到另一个类的实例的属性(两者之间的公共字段).请参阅以下示例:
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属性:class的属性:Two
解决方法
问题是,对于每个对象,.properties包括两个内置的Groovy定义属性,这些属性是metaClass和类.您要做的只是设置用户定义的属性.您可以使用如下所示的代码轻松完成此操作:
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