2011-04-07 59 views
1

夥計! 我希望能夠動態導航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://stackoverflow.com/questions/5488689/how-to-retrieve-nested-properties-in-groovy) – 2011-04-07 08:55:11

回答

1

這可以通過覆蓋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' 
}