在test.groovy
中进行以下设置:
class Main {
public static void main(String ... args) {
new Child().foo()
}
public static class Parent {
def foo() {
println 'from parent'
}
}
public static class Child extends Parent {
def foo() {
// def superRef = super.&foo // needed to try what’s commented below
def myClosure = {
super.foo() // doesn’t work, neither does anything of the following:
// this.super.foo()
// Child.super.foo()
// Child.this.super.foo()
// superRef()
println 'from child'
}
myClosure()
}
}
}
当我运行groovy test.groovy
(使用Groovy 2.5.4和至少我尝试过的所有其他版本)时,出现以下错误:
Caught: groovy.lang.MissingMethodException: No signature of method: static Main.foo() is applicable for argument types: () values: []
Possible solutions: any(), find(), use([Ljava.lang.Object;), is(java.lang.Object), any(groovy.lang.Closure), find(groovy.lang.Closure)
groovy.lang.MissingMethodException: No signature of method: static Main.foo() is applicable for argument types: () values: []
Possible solutions: any(), find(), use([Ljava.lang.Object;), is(java.lang.Object), any(groovy.lang.Closure), find(groovy.lang.Closure)
at Main$Child.methodMissing(test.groovy)
at Main$Child$_foo_closure1.doCall(test.groovy:16)
at Main$Child$_foo_closure1.doCall(test.groovy)
at Main$Child.foo(test.groovy:23)
at Main$Child$foo.call(Unknown Source)
at Main.main(test.groovy:3)
如何从子类(Parent.foo
的相应方法所包围的闭包(myClosure
)中引用超类方法(Child.foo
)?
(背景:执行我的myCloseable.withCloseable { super.foo(); … }
之类的操作需要关闭我的实际代码)
答案 0 :(得分:1)
闭包-它是另一个类(就Java而言),您不能从另一个类访问super方法。
IHMO唯一方法:
class Main {
public static void main(String ... args) {
new Child().foo()
}
public static class Parent {
def foo() {
println 'from parent'
}
}
public static class Child extends Parent {
def superFoo(){
super.foo()
}
def foo() {
def myClosure = {
superFoo()
println 'from child'
}
myClosure()
}
}
}