【问题标题】:Dynamic object graph navigation in GroovyGroovy 中的动态对象图导航
【发布时间】:2011-04-07 08:28:38
【问题描述】:

伙计们! 我希望能够动态导航 Groovy 对象图,路径为字符串:

def person = new Person("john", new Address("main", new Zipcode("10001", "1234")))
def path = 'address.zip.basic'

我知道我可以访问地图符号中的属性,但它只有一层:

def path = 'address'
assert person[path] == address

有没有办法评估更深层次的路径?

谢谢!

【问题讨论】:

标签: groovy


【解决方案1】:

这可以通过重写getAt 运算符并遍历属性图来实现。以下代码使用 Groovy Category,但也可以使用继承或混合。

class ZipCode {
    String basic
    String segment

    ZipCode(basic, segment) {
        this.basic = basic
        this.segment = segment
    }
}

class Address {
    String name
    ZipCode zip

    Address(String name, ZipCode zip) {
        this.name = name
        this.zip = zip
    }
}

class Person {
    String name
    Address address

    Person(String name, Address address) {
        this.name = name
        this.address = address
    }

}

@Category(Object)
class PropertyPath {

    static String SEPARATOR = '.'

    def getAt(String path) {

        if (!path.contains(SEPARATOR)) {
            return this."${path}"
        }

        def firstPropName = path[0..path.indexOf(SEPARATOR) - 1]
        def remainingPath = path[path.indexOf(SEPARATOR) + 1 .. -1]
        def firstProperty = this."${firstPropName}"
        firstProperty[remainingPath]
    }
}

def person = new Person('john', new Address('main', new ZipCode('10001', '1234')))

use(PropertyPath) {
    assert person['name'] == 'john'
    assert person['address.name'] == 'main'
    assert person['address.zip.basic'] == '10001'
}

PropertyPath.SEPARATOR = '/'
use(PropertyPath) {
    assert person['address/zip/basic'] == '10001'
}

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2011-09-27
    • 2023-02-09
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    相关资源
    最近更新 更多