Groovy 如何向闭包添加属性?
当我尝试向自定义闭包类添加属性时Groovy 如何向闭包添加属性?,groovy,closures,Groovy,Closures,当我尝试向自定义闭包类添加属性时 class MyClosure extends Closure<Object> { def myProperty MyClosure() { super(null) } Object doCall(final Closure inner) { // do something... } } println new MyClosure().myProperty 这似乎与闭包类有关,
class MyClosure extends Closure<Object> {
def myProperty
MyClosure() {
super(null)
}
Object doCall(final Closure inner) {
// do something...
}
}
println new MyClosure().myProperty
这似乎与闭包类有关,闭包类有一些我不太理解的行为,因为当我删除implements
部分时,没有问题:
class MyClosure {
def myProperty
}
println new MyClosure().myProperty
那么,当我想向自定义闭包添加属性时,我需要做什么呢?您需要更改闭包解析策略:
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
类MyClosure扩展了Closure{
def myProperty=“值”
MyClosure(){
超级(空)
}
对象doCall(最终闭包内部){
//做点什么。。。
}
}
def closure=new MyClosure()
closure.resolveStrategy=closure.TO_SELF
println closure.myProperty//value
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