如何检索groovy中的嵌套属性 [英] how to retrieve nested properties in groovy

查看:163
本文介绍了如何检索groovy中的嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是在Groovy中检索嵌套属性的最佳方法,可以使用给定的对象和任意的属性字符串。我想这样的事情:

  someGroovyObject.getProperty(property1.property2)

我很难找到其他人希望这样做的例子,所以也许我不了解一些基本的Groovy概念。看来,必须有一些优雅的方式来做到这一点。



作为参考,Wicket中有一个功能正是我正在寻找的功能,称为PropertyResolver :
http://wicket.apache.org/apidocs /1.4/org/apache/wicket/util/lang/PropertyResolver.html



任何提示将不胜感激!


<我不知道Groovy是否有内置的方式来做到这一点,但这里有2个解决方案。在 Groovy Console 中运行此代码以进行测试。

  def getProperty(object,String property){

property.tokenize('。')。inject object,{obj,prop - >
obj [prop]
}
}

//定义一些用于测试的类
class Name {
String first
字符串第二个
}

类Person {
名称
}

//创建一个在测试中使用的对象
Person person = new Person(name:new Name(first:'Joe',second:'Bloggs'))

//运行测试
assert'Joe'= = getProperty(person,'name.first')

/////////////////////////////// //////////
//替代实施
//////////////////////////// // b $ b def evalProperty(object,String property){
Eval.x(object,'x。'+ property)
}

//测试替代实现
assert'Bloggs'== evalProperty(person,'name.second')


I'm wondering what is the best way to retrieve nested properties in Groovy, taking a given Object and arbitrary "property" String. I would like to something like this:

someGroovyObject.getProperty("property1.property2")

I've had a hard time finding an example of others wanting to do this, so maybe I'm not understanding some basic Groovy concept. It seems like there must be some elegant way to do this.

As reference, there is a feature in Wicket that is exactly what I'm looking for, called the PropertyResolver: http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/lang/PropertyResolver.html

Any hints would be appreciated!

解决方案

I don't know if Groovy has a built-in way to do this, but here are 2 solutions. Run this code in the Groovy Console to test it.

def getProperty(object, String property) {

  property.tokenize('.').inject object, {obj, prop ->       
    obj[prop]
  }  
}

// Define some classes to use in the test
class Name {
  String first
  String second
}

class Person {
  Name name
}

// Create an object to use in the test
Person person = new Person(name: new Name(first: 'Joe', second: 'Bloggs'))

// Run the test
assert 'Joe' == getProperty(person, 'name.first')

/////////////////////////////////////////
// Alternative Implementation
/////////////////////////////////////////
def evalProperty(object, String property) {
  Eval.x(object, 'x.' + property)
}

// Test the alternative implementation
assert 'Bloggs' == evalProperty(person, 'name.second')

这篇关于如何检索groovy中的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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