当我尝试将属性添加到自定义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
这似乎与Closure类有关,我有一些行为我并不理解,因为当我删除implements
部分时没有问题:
class MyClosure {
def myProperty
}
println new MyClosure().myProperty
那么当我想将属性添加到自定义闭包时,我需要做什么?
答案 0 :(得分: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