【发布时间】:2017-10-27 13:19:27
【问题描述】:
例如,Groovy 中的这段代码运行良好:
def f = new Runnable() {
def test = "Hello!"
@Override
void run() {
println(test)
}
}
f.run()
它将Hello! 打印到控制台。这里的主要思想是它在匿名类中使用实例变量。
但是当你将这样的匿名类实例化移动到枚举常量的参数时,现在它不起作用了:
enum E {
E1(new Runnable() {
def test = "Hello!"
@Override
void run() {
println(test)
}
})
def runnable
E(def r) {
runnable = r
}
}
E.E1.runnable.run()
控制台显示错误:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
ideaGroovyConsole.groovy: 23: Apparent variable 'test' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'test' but left out brackets in a place not allowed by the grammar.
@ line 23, column 21.
println(test)
^
它说在静态范围内找到了变量(为什么?),但它甚至不能将它用作静态字段。
但是,它可以在匿名类中没有变量的情况下工作:
enum E {
E1(new Runnable() {
@Override
void run() {
println("Hello!")
}
})
def runnable
E(def r) {
runnable = r
}
}
E.E1.runnable.run()
如何强制 Groovy 像在 Java 中一样使用匿名类中的实例变量?
【问题讨论】:
-
内部类是 Groovy 偏离 Java 的领域之一:groovy-lang.org/differences.html#_inner_classes
-
@bdkosher 是的,我已经读过这个here 但是我的问题中的问题让我感到惊讶,然后提到了链接上的差异
标签: groovy enums anonymous-class