简体   繁体   English

为什么Groovy Enums无法访问类变量?

[英]Why Groovy Enums has no access to class variables?

Could not find any documentation that explains why class variables are not accessible from within enums. 找不到任何解释为什么无法从枚举中访问类变量的文档。 Consider this example: 考虑这个例子:

package groovy;

public class Universe {

    static String test = "test";

    enum Planet {

        EARTH {
            @Override
            void doSomething(){
                System.out.print(test);
            }
        };

        abstract void doSomething();
    }

    public static void main(String[] args) {
        Universe.Planet.EARTH.doSomething(); // No such property: test for class: groovy.Universe$Planet$1
    }
}

I am aware that this code is also perfect Java code. 我知道这段代码也是完美的Java代码。 Though it works as expected using JRE but not with Groovy's runtime environment which makes me even more curious. 虽然它使用JRE按预期工作,但不是Groovy的运行时环境,这让我更加好奇。 Is there any proof for the difference? 有什么区别的证据吗? Thanks 谢谢

Groovy needs some help to find Universe's variable. Groovy需要一些帮助才能找到Universe的变量。 Here's a link to some official documentation if you want to read up on a few differences between Java and Groovy. 如果您想了解Java和Groovy之间的一些差异,这里是一些官方文档的链接。 Here's an email discussion that touches on this some. 这是一个涉及这个问题电子邮件讨论 For anyone unfamiliar with enums, they're static objects, so no accessing instance objects or variables. 对于不熟悉枚举的人来说,它们是静态对象,因此不能访问实例对象或变量。 Which leads us to our answer, static variable needs to be referenced in a static way (via class, not an instance). 这引出了我们的答案,静态变量需要以静态方式引用(通过类,而不是实例)。
Also, if you try to use inner classes before Groovy 1.7 you're going to have a bad time (you can't). 此外,如果你尝试在Groovy 1.7之前使用内部类,那么你将会遇到一个糟糕的时间(你不能)。

public class Universe {

static String test = "testing";

enum Planet {

    EARTH {
        @Override
        void doSomething(){
            System.out.print(Universe.test);
        }
    };

    abstract void doSomething();
}

public static void main(String[] args) {
    Universe.Planet.EARTH.doSomething(); // No such property: test for class: groovy.Universe$Planet$1
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM