클로저가 구현되는 수퍼 클래스 대신 실제 클래스로 실행되어 일부 변수가 표시되지 않을 때 중단된다는 인상을받습니다 (예 : private in 수퍼 클래스). 예를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 사용자 메일 링리스트에서 더 잘 묻습니다. –
Ok, 감사합니다. Tim, 알겠습니다. – user1070984