Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object properties in groovy using []

Tags:

groovy

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?

like image 278
Valdemar Avatar asked Nov 02 '10 11:11

Valdemar


2 Answers

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' ]
like image 59
tim_yates Avatar answered Sep 30 '22 17:09

tim_yates


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]]
like image 43
Augusto Avatar answered Sep 30 '22 18:09

Augusto