Java 为什么我在 case 标签中得到一个 Enum 常量引用不能被限定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2663980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:31:44  来源:igfitidea点击:

Why do I get an Enum constant reference cannot be qualified in a case label?

javaenums

提问by maleki

Why does the following code fail to compile, while changing the case statement to

为什么下面的代码编译失败,同时将case语句改为

case ENUM1: doSomeStuff();

works?

作品?

public enum EnumType
{
    ENUM1, ENUM2, ENUM3;

    void doSomeStuff()
    {
        switch(this)
        {
        case EnumType.ENUM1: doSomeStuff();
        }
    }
}

采纳答案by BalusC

This is to avoid the ability to compare against different enum types. It makes sense to restrict it to onetype, i.e. the type of the enum value in the switchstatement.

这是为了避免与不同的枚举类型进行比较的能力。将其限制为一种类型是有意义的,即switch语句中枚举值的类型。

Update: it's actually to keep binary compatibility. Here's a cite from about halfway chapter 13.4.9of JLS:

更新:实际上是为了保持二进制兼容性。这是 JLS大约一半的章节 13.4.9的引用:

One reason for requiring inlining of constants is that switchstatements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switchstatement at compile time; the classfile format does not do symbolic linkage of case values.

需要内联常量的一个原因是switch语句需要在 each 上有常量case,并且没有两个这样的常量值可能相同。编译器switch在编译时检查语句中的重复常量值;该class文件格式没有做的情况下价值观的象征性的联系。

In other words, because of the class identifier in EnumType.ENUM1, it cannot be represented as a compiletime constant expression, while it is required by the switchstatement.

换句话说,由于类标识符 in EnumType.ENUM1,它不能表示为编译时常量表达式,而它是switch语句所必需的。

回答by ColinD

Since you're switching on an object of type EnumTypeand the only possible values for it are the enum constants, there's no need to qualify those constants again in within the switch. After all, it would be illegal to have case OtherEnumType.ENUM1:in it anyway.

由于您正在切换类型的对象,EnumType并且它唯一可能的值是枚举常量,因此无需在切换中再次限定这些常量。毕竟,case OtherEnumType.ENUM1:无论如何,拥有它都是非法的。

回答by J?rn Horstmann

This is not really answering your question but if you have code depending on the enum value, you can also create an abstract method in your enum that gets overloaded for every value:

这并没有真正回答您的问题,但是如果您有依赖于枚举值的代码,您还可以在枚举中创建一个抽象方法,该方法为每个值重载:

public enum EnumType {
    ENUM1 {
        @Override
        public void doSomeStuff() {
            // do something
        }
    },
    ENUM2 {
        @Override
        public void doSomeStuff() {
            // do something else
        }
    };

    public abstract void doSomeStuff();
}