如何在groovy中检索嵌套属性

Nat*_*ach 10 groovy nested properties getproperty resolver

我想知道在Groovy中检索嵌套属性的最佳方法是什么,获取给定的Object和任意"property"字符串.我想这样的事情:

someGroovyObject.getProperty("property1.property2")
Run Code Online (Sandbox Code Playgroud)

我很难找到其他人想要这样做的例子,所以也许我不理解一些基本的Groovy概念.似乎必须有一些优雅的方式来做到这一点.

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

任何提示将不胜感激!

Dón*_*nal 25

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

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')
Run Code Online (Sandbox Code Playgroud)