Groovy 在枚举内的匿名类中声明实例变量
例如,Groovy中的这段代码运行良好:Groovy 在枚举内的匿名类中声明实例变量,groovy,enums,anonymous-class,Groovy,Enums,Anonymous Class,例如,Groovy中的这段代码运行良好: def f = new Runnable() { def test = "Hello!" @Override void run() { println(test) } } f.run() 它打印你好到控制台。这里的主要思想是在匿名类中使用实例变量。 但是,当您将此类匿名类实例化移动到enum常量的参数时,它现在不起作用: enum E { E1(new Runnable() {
def f = new Runnable() {
def test = "Hello!"
@Override
void run() {
println(test)
}
}
f.run()
它打印你好代码>到控制台。这里的主要思想是在匿名类中使用实例变量。
但是,当您将此类匿名类实例化移动到enum常量的参数时,它现在不起作用:
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也可以这样做,尽管您必须使用这个来参考测试字段。测试字段访问符号以满足groovyc编译器的要求:
enum E {
E1(new Runnable() {
def test = "Hello!"
@Override
void run() {
println(this.test)
}
})
def runnable
E(def r) {
runnable = r
}
}
E.E1.runnable.run()
内部类是Groovy有点偏离Java的领域之一:@bdkosher是的,我读过这篇文章,但我问题中的问题让我感到惊讶,然后提到链接上的差异太简单了!非常感谢。