Say I have the following code in groovy:
class Human {
Face face
}
class Face {
int eyes = 2
}
def human = new Human(face:new Face())
I want to access the eyes
property using the []
:
def humanProperty = 'face.eyes'
def value = human[humanProperty]
But this does not work as I expected (as this tries to access a property named 'face.eyes' on the Human object, not the eyes property on the human.face property).
Is there another way to do this?
You would need to evaluate the string to get to the property you require. To do this, you can either do:
humanProperty.split( /\./ ).inject( human ) { obj, prop -> obj?."$prop" }
(that splits the humanProperty
into a list of property names, then, starting with the human
object, calls each property in turn, passing the result to the next iteration.
Or, you could use the Eval class to do something like:
Eval.x( human, "x.${humanProperty}" )
To use the []
notation, you would need to do:
human[ 'face' ][ 'eyes' ]
An easier way would be to simply execute:
def value = human['face']['eyes']
But if you don't know the values required ('face' and 'eyes'), there's also an easier and clearer way.
def str = "face.eyes"
def values = str.split("\\.")
def value = human[values[0]][values[1]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With