我有一个印象,即闭包运行时被调用的实际类(而不是实现的超类),因此当某些变量不可见时就会中断(例如private超级类)。groovy:超类中的闭包中的变量范围(MissingPropertyException)
例如
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:子类调用父类,它执行“每一个”封,它使用“accessThisPrivateVariable”的“添加”方法。
我是新来的groovy,所以我认为必须有一个简单的方法来做到这一点,因为否则似乎闭包完全打破了在超类中完成的私有实现的封装......这似乎是非常普遍的需求(超类实现引用自己的私有变量)
我使用Groovy 2.1.3
至于你的其他问题,这可能是更好的在groovy用户邮件列表 – 2013-04-24 13:49:01
问,好吧,谢谢蒂姆,我会这样做 – user1070984 2013-04-24 14:20:55