miércoles, octubre 09, 2013

Groovy: Dynamic access to nested properties via GString

In groovy you can easily access properties by using GString which a really cool feature.

Map data=[
one:"john",
two:"mary"
]
String entry="two"
println data."${entry}" //"mary"

However this trick doesnt work when nested '.' are inside de expression.

In this case you can do the following:
Map data=[
one:[
two:"2222",
three:"333"
]
]
String nestedExpression="one.two"
String output=nestedExpression.tokenize('.').inject(data) {v, k -> v."$k"}
println output // "2222"

That's all!