[SOLVED] Groovy dynamic object properties from string get and set

If you need to evaluate some properties of an object from strings like:
person.”name.first”

person is

[code]
class Person {
Name name
}
class Name {
String first
String second
}
[/code]

then

[code]
def evalProperty(object, String property) {
Eval.x(object, ‘x.’ + property)
}
[/code]
And the setter 🙂
[code]
void setProperty(Object object, String propertyPath, Object value) {
def pathElements = propertyPath.tokenize(‘.’)
Object parent = evalProperty(object, pathElements[0..-2].join(‘.’))
parent[pathElements[-1]] = value
}
[/code]

use:
[code]
evalProperty(person, ‘name.first’)
setProperty(person,’name.first’,’New Name’)
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *