更新时间:2023-12-05 13:29:40
您需要引用外部"类(实际上不是外部类).
You need a reference to the "outer" class (which isn't really an outer class).
假定您将代码编写在 Script.groovy
文件中,它将生成两个类: C.class
和 Script.class
.由于无法确定在哪里定义,因此无法通过 C
调用 f()
方法.
Assuming you are writing your code in a Script.groovy
file, it generates two classes: C.class
and Script.class
. There is no way to the C
call the f()
method, since it has no idea where it is defined.
您有一些选择:
1) @MichaelEaster的想法,从当前范围(即 Script
)给出元类定义
1) @MichaelEaster's idea, giving a metaclass defition from the current scope (i.e. Script
)
2)在 C
内创建/传递 Script
对象:
2) Create/pass a Script
object inside C
:
def f() { "f" }
class C
{
public h(s = new Script()) { s.f() }
}
assert "f" == new C().h()
3)将 C
设置为内部类(还需要 Script
的实例:
3) Make C
an inner class (which also needs an instance of Script
:
class Script {
def f() { "f" }
class C
{
public h() { f() }
}
static main(args) {
assert "f" == new C(new Script()).h()
}
}
4):静态内部类以及静态 f()
:
4) Static inner class plus static f()
:
class Script {
static def f() { "f" }
static class C
{
public h() { f() }
}
static main(args) {
assert "f" == new C().h()
}
}