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 }
dynamic groovy
Jim gough
source share