在枚举内的匿名类中声明实例变量

时间:2017-10-27 13:19:27

标签: groovy enums anonymous-class

例如,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中的匿名类中的实例变量?

1 个答案:

答案 0 :(得分:4)

虽然你必须使用test字段访问符号来引用this.test字段来满足groovyc编译器,但它仍然适用于Groovy:

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()