简体   繁体   English

使用[]访问groovy中的对象属性

[英]Access object properties in groovy using []

Say I have the following code in groovy: 说我在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 [] : 我想使用[]访问eyes属性:

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). 但这并不像我预期的那样工作(因为它试图在Human对象上访问名为'face.eyes'的属性,而不是在human.face属性上访问eyes属性)。

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. (将humanProperty拆分为属性名称列表,然后,从human对象开始,依次调用每个属性,将结果传递给下一次迭代。

Or, you could use the Eval class to do something like: 或者,您可以使用Eval类来执行以下操作:

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM