加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何在groovy中检索嵌套属性

发布时间:2020-12-14 16:34:08 所属栏目:大数据 来源:网络整理
导读:我想知道在Groovy中检索嵌套属性的最佳方法是什么,获取给定的Object和任意“property”字符串.我想这样的事情: someGroovyObject.getProperty("property1.property2") 我很难找到其他人想要这样做的例子,所以也许我不理解一些基本的Groovy概念.似乎必须有一
我想知道在Groovy中检索嵌套属性的最佳方法是什么,获取给定的Object和任意“property”字符串.我想这样的事情:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读