I have a path for an object within an object within an object and I want to set it using Groovy's dynamic abilities. Usually you can do so just by doing the following:
class Foo {
String bar
}
Foo foo = new Foo
foo."bar" = 'foobar'
That works OK. But what if you have nested objects? Something like:
class Foo {
Bar bar
}
class Bar {
String setMe
}
Now I want to use the dynamic setting, but
Foo foo = new Foo()
foo."bar.setMe" = 'This is the string I set into Bar'
Returns a MissingFieldException.
Any hints?
UPDATE: Thanks to Tim for pointing me in the right direction, the initial code on there works great at retrieving a property, but I need to set the value using the path string.
Here's what I came up with from the page Tim suggested:
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
}