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

后端 未结 3 1623
你的背包
你的背包 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.

提交回复
热议问题