如何从Groovy中的对象获取嵌套的属性值? [英] How to get nested property value from object in Groovy?

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

问题描述

考虑在Groovy中键入Company的情况:

Consider situation where in Groovy you have type Company:

class Company {
  def name
  def contactPerson
}

contactPersonContact类型:

class Contact {
  def firstName
  def lastName
  def email
}

然后我们有Company类的实例:

Then we have instance of Company class:

def stackOverflow = new Company(
  name: "Stack Overflow",
  contactPerson: new Contact(
    firstName: "Joel",
    lastName: "Spolsky",
    email: "joel.spolsky@stackoverflow.com"
  )
)

在Groovy中,我们简单地拥有:

In Groovy we simple have:

assert stackOverflow.contactPerson.firstName == "Joel"

或:

assert stackOverflow['contactPerson']['firstName'] == "Joel"

还有:

assert stackOverflow.name == "Stack Overflow"

或:

assert stackOverflow['name'] == "Stack Overflow"

甚至:

def fieldName = 'name'
assert stackOverflow.${fieldName} == "Stack Overflow"

但是假设我们有:

def nestedFieldName = 'contactPerson.firstName'

是否有实现这种目标的Groovy方式:

Is there a Groovy-way to achieve something like this:

assert stackOverflow.${nestedFieldName} == "Joel"

?

推荐答案

一种方法是减少键序列:

One approach is to reduce a sequence of keys:

nestedFieldName.split('\\.')
    .inject(stackOverflow) { object, property -> 
        object[property]
     }

哪个返回'Joel',可用于读取任意深度的值.

Which returns 'Joel', and could be used to read values at arbitrary depths.

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

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