Groovy中的动态对象图导航

问题描述:

伙计! 我希望能够动态导航Groovy的对象图,具有字符串的路径:我知道,我可以访问地图符号属性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 

有什么方法可以评估更深的路径吗?

谢谢!

+0

可能重复的[如何检索在常规嵌套属性(http://*.com/questions/5488689/how-to-retrieve-nested-properties-in-groovy) – 2011-04-07 08:55:11

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

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' 
}