【发布时间】:2013-04-18 02:32:45
【问题描述】:
我的印象是闭包作为被调用的实际类(而不是实现的超类)运行,因此当某些变量不可见时会中断(例如超类中的私有)。
例如
package comp.ds.GenericTest2
import groovy.transform.CompileStatic
@CompileStatic
class ClosureScopeC {
private List<String> list = new ArrayList<String>()
private int accessThisPrivateVariable = 0;
void add(String a) {
list.add(a)
println("before ${accessThisPrivateVariable} ${this.class.name}")
// do something with a closure
list.each {String it ->
if (it == a) {
// accessThisPrivateVariable belongs to ClosureScopeC
accessThisPrivateVariable++
}
}
println("after ${accessThisPrivateVariable}")
}
}
// this works fine
a = new ClosureScopeC()
a.add("abc")
a.add("abc")
// child class
class ClosureScopeD extends ClosureScopeC {
void doSomething(String obj) {
this.add(obj)
}
}
b = new ClosureScopeD()
// THIS THROWS groovy.lang.MissingPropertyException: No such property: accessThisPrivateVariable for class: comp.ds.GenericTest2.ClosureScopeD
b.doSomething("abc")
最后一行抛出一个 MissingPropertyException:子类调用超类的“add”方法,该方法执行“each”闭包,该闭包使用“accessThisPrivateVariable”。
我是 groovy 的新手,所以我认为必须有一个简单的方法来做到这一点,因为否则看起来闭包会完全破坏超类中完成的私有实现的封装......这似乎是一个非常共同需求(超类实现引用自己的私有变量)
我正在使用 groovy 2.1.3
【问题讨论】:
-
与您的其他问题一样,这可能最好在 groovy-user 邮件列表中提出
-
好的,谢谢蒂姆,我会这样做的
标签: groovy scope closures superclass