如何从Groovy中的对象获取嵌套的属性值?

时间:2018-06-20 11:53:32

标签: groovy

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

class Company {
  def name
  def contactPerson
}

contactPerson类型的Contact

class Contact {
  def firstName
  def lastName
  def email
}

然后我们有Company类的实例:

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

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

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方法:

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

1 个答案:

答案 0 :(得分:6)

一种方法是减少键序列:

select LastUpdated, Remarks
from table
where (remarks = 'Others' and datediff(min, LastUpdated, GETDATE()) > 15)
      or remarks != 'Others'

哪个返回TOP x,可用于读取任意深度的值。