2014-04-09 65 views
1

這是行不通的。不應該嗎?Groovy擴展hashmap與字段

class WeirdBean extends HashMap { 
    public String inner = "set within" 
    def getInner() { return this.inner } 
    def getOuter() { return this.outer } 
} 

def o = WeirdBean.newInstance() 
o.outer = "set without" 
println o.getOuter() // set without 
println o.outer  // set without 
assert o.outer == o.getOuter() // Pass 

println o.getInner() // set within 
println o.inner  // null, even though public 
assert o.inner == o.getInner() // Fail, o.inner is null 
+2

要直接訪問字段,你必須使用'o。@內部'否則'o.inner'將被視爲獲取鍵'這裏明顯是'null' – dmahapatro

回答

1

好像Map::getobject.fieldobject.property更高的優先級。因爲裏面的字段訪問一個類不通過getter,這個工作:

class WeirdBean extends HashMap { 
    public String inner = "set within" 
    def getInner() { return this.inner } 

    def getProperty(String property) { 
    (property == 'inner') ? inner : super.get(property) 
    } 

    def getOuter() { return this.outer } 
} 

def o = WeirdBean.newInstance() 
o.outer = "set without" 
println o.getOuter() // set without 
println o.outer  // set without 
assert o.outer == o.getOuter() // Pass 

println o.getInner() // set within 
println o.inner  // null, even though public 
assert o.inner == o.getInner() // Fail, o.inner is null 
+0

getProperty()是門票,那麼謝謝。 – inyourcorner

+0

setProperty()看起來像仍然在類中設置該屬性時被調用(例如, this.inner =「newthing」),這與常規豆不同,正是我尋找的奇怪/功能 – inyourcorner

+1

哇。如果只有在物業不存在的情況下才需要,還有'propertyMissing'。 – Will

1

表達式o.inner從HashMap返回鍵。有沒有這樣的關鍵inner所以會返回空值,而裏面this.inner場的getInner()方法返回值是(被設定爲"set without"。這就是爲什麼。