Groovy: setting a dynamic nested method using a string as a path

I have a path to an object inside an object inside an object, and I want to set it using the Groovy dynamic capabilities. You can usually do this by doing the following:

class Foo { String bar } Foo foo = new Foo foo."bar" = 'foobar' 

This is working fine. But what if you have nested objects? Something like:

 class Foo { Bar bar } class Bar { String setMe } 

Now I want to use dynamic settings, but

 Foo foo = new Foo() foo."bar.setMe" = 'This is the string I set into Bar' 

Throws a MissingFieldException.

Any clues?

UPDATE: Thanks Tim for pointing me in the right direction, the source code there works fine when retrieving the property, but I need to set the value using the path string.

Here is what I came up with from Tim’s page:

  def getProperty(object, String propertyPath) { propertyPath.tokenize('.').inject object, {obj, prop -> obj[prop] } } void setProperty(Object object, String propertyPath, Object value) { def pathElements = propertyPath.tokenize('.') Object parent = getProperty(object, pathElements[0..-2].join('.')) parent[pathElements[-1]] = value } 
+5
dynamic groovy
source share
1 answer

It works correctly.

 foo."bar"."setMe" = 'This is the string I set into Bar'; 

Without overriding getProperty, you can achieve the same result using the $ {} "syntax for GString, as shown below,

 class Baz { String something } class Bar { Baz baz } class Foo { Bar bar } def foo = new Foo() foo.bar = new Bar() foo.bar.baz = new Baz() def target = foo def path = ["bar", "baz"] for (value in path) { target = target."${value}" } target."something" = "someValue" println foo.bar.baz.something 

final println prints "someValue" as expected

+1
source share

All Articles