使用对象访问属性。“$ {property}” [英] Accessing a property with object."${property}"

查看:92
本文介绍了使用对象访问属性。“$ {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在Groovy Web控制台上提供一个工作示例


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}”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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