Groovy – 将属性从一个对象绑定到另一个对象
发布时间:2020-12-14 16:36:30 所属栏目:大数据 来源:网络整理
导读:有没有办法将属性从一个类的实例绑定到另一个类的实例的属性(两者之间的公共字段).请参阅以下示例: 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()t
有没有办法将属性从一个类的实例绑定到另一个类的实例的属性(两者之间的公共字段).请参阅以下示例:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |