使用 [] 访问 groovy 中的对象属性 [英] Access object properties in groovy using []

查看:17
本文介绍了使用 [] 访问 groovy 中的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 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())

我想使用 [] 访问 eyes 属性:

I want to access the eyes property using the []:

def humanProperty = 'face.eyes'
def value = human[humanProperty]

但这并不像我预期的那样工作(因为它试图访问 Human 对象上名为face.eyes"的属性,而不是 human.face 属性上的 eyes 属性).

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" }

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

(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.

或者,您可以使用 Eval 类执行以下操作:

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

这篇关于使用 [] 访问 groovy 中的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆