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

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

问题描述

  class Human {
面对面
}
class Face {
int eyes = 2
}
def human = new Human(face:new Face())
pre>

我想使用 [] 眼睛属性
$ b $ pre $ def humanProperty ='face.eyes'
def value = human [humanProperty]

但是这不起作用,因为我试图访问一个名为'face.eyes'的属性人类对象,而不是human.face属性的眼睛属性)。

是否有另一种方法可以做到这一点?

解决方案

您需要评估字符串以获取所需的属性。要做到这一点,你可以这样做:

  humanProperty.split(/\./).inject(human){obj ,道具 - > obj?。$ prop} 

(即分割 humanProperty 放入属性名称列表中,然后从人类对象开始,依次调用每个属性,并将结果传递给下一次迭代。



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

  Eval .x(human,x。$ {humanProperty})

要使用<$ c $

  human ['face'] [c] []  'eyes'] 


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

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

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