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

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

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...