使用对象访问属性

使用对象访问属性

本文介绍了使用对象访问属性。“$ {property}”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class可筛选{
def statusId
def secondaryFilterable

...
def filter = new Filter(validIds:[1],fieldName:'statusId')
...
class Filter {

def validIds = [] as Set
def fieldName
private boolean containsFieldValue(input){
def fieldValue = input。$ {fieldName}
return fieldValue in validIds
}
}

罚款一个财产。然而,现在我需要通过二次过滤来过滤 - 就像

  def filter = new Filter(validIds:[1], fieldName:'secondaryFilterable.statusId')

抛出 groovy.lang。 MissingPropertyException 。任何建议?

解决方案

引用的属性假定一个点是属性名称的一部分。 $ b

一个简单的解决方案是:

  ... 
def fieldValue = fieldName.split(/ \ ./)。inject(input){parent,property - > parent?。$ property}
...

这将递归查找字段值,使用点符号表示子元素。




I'm working on some dynamic filtering, and have this:

class Filterable {
    def statusId
    def secondaryFilterable
}
...
def filter = new Filter(validIds: [1], fieldName: 'statusId')
...
class Filter {

    def validIds = [] as Set
    def fieldName
    private boolean containsFieldValue(input) {
        def fieldValue = input."${fieldName}"
        return fieldValue in validIds
    }
}

Which works just fine for one property. However, now I need to filter by the secondary filterable - something like

def filter = new Filter(validIds: [1], fieldName: 'secondaryFilterable.statusId')

Which throws a groovy.lang.MissingPropertyException. Any advice?

解决方案

Quoted properties assume a dot is part of the property name.

A simple solution would be:

...
def fieldValue = fieldName.split(/\./).inject(input){ parent, property -> parent?."$property" }
...

This will recursively look up the field value using dot notation for child properties.

I put up a working example here on the Groovy web console.

这篇关于使用对象访问属性。“$ {property}”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:32