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

后端 未结 3 1620
你的背包
你的背包 2020-12-08 06:42

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

case ENUM1: doSomeStuff();

works?

public          


        
相关标签:
3条回答
  • 2020-12-08 07:01

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

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

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

    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 switch statement.

    0 讨论(0)
  • 2020-12-08 07:13

    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();
    }
    
    0 讨论(0)
  • 2020-12-08 07:22

    Since you're switching on an object of type EnumType and 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.

    0 讨论(0)
提交回复
热议问题