我想知道在 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]
}
}
// 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 - 如何在groovy中检索嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5488689/