【问题标题】:Declare instance variable in anonymous class inside enum在枚举内的匿名类中声明实例变量
【发布时间】: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 enums anonymous-class


【解决方案1】:

这也适用于 Groovy,尽管您必须使用 this.test 字段访问表示法来引用 test 字段以满足 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()

【讨论】:

  • 这么简单!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多