Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy - bind properties from one object to another

Tags:

groovy

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

like image 523
vv. Avatar asked Dec 08 '22 06:12

vv.


2 Answers

I would choose InvokerHelper.setProperties as I suggesed here.

use(InvokerHelper) {
    two.setProperties(one.properties)
}
like image 59
Michal Z m u d a Avatar answered Dec 09 '22 19:12

Michal Z m u d a


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
like image 44
Dónal Avatar answered Dec 09 '22 20:12

Dónal