2017-01-22 56 views
0

當我試圖將屬性添加到自定義closure類...如何給閉包添加屬性?

class MyClosure extends Closure<Object> { 
    def myProperty 
    MyClosure() { 
     super(null) 
    } 
    Object doCall(final Closure inner) { 
     // do something... 
    } 
} 
println new MyClosure().myProperty 

我得到一個錯誤:

java.lang.NullPointerException: Cannot get property 'myProperty' on null object 

看來,這是關係到,有一些行爲類閉幕我真的不明白,當我刪除implements部分沒有任何問題:

class MyClosure { 
    def myProperty 
} 
println new MyClosure().myProperty 

那麼我需要做的,當我想添加一個公關操作自定義閉包?

回答

1

您需要更改關閉解決策略:

class MyClosure extends Closure<Object> { 
    def myProperty = "value" 

    MyClosure() { 
     super(null) 
    } 

    Object doCall(final Closure inner) { 
     // do something... 
    } 
} 

def closure = new MyClosure() 
closure.resolveStrategy = Closure.TO_SELF 
println closure.myProperty // value 
+0

完美的作品,謝謝! – nepa