23

(note: edited question; the prior intent was not clear)

Consider this code:

public final class Foo
{
    private enum X
    {
        VALUE1, VALUE2
    }

    public static void main(final String... args)
    {
        final X x = X.VALUE1;

        switch (x) {
            case VALUE1:
                System.out.println(1);
                break;
            case VALUE2:
                System.out.println(2);
        }
    }
}

This code works fine.

However, if I replace:

case VALUE1: // or VALUE2

with:

case X.VALUE1: // or X.VALUE2

then the compiler complains:

java: /path/to/Foo.java:whatever: an enum switch case label must be the unqualified name of an enumeration constant

SO suggests an answer with this quote from the 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.)

But this does not satisfy me. As far as I am concerned, VALUE1 and X.VALUE1 are exactly the same. The quoted text does not explain it at all for me.

Where in the JLS is it defined that enum values in switch statements have to be written this way?

4

1 回答 1

10

SwitchLabel需要一个EnumConstantName,它被定义为枚举常量标识符,它是不合格的

EnumConstant:
Annotations opt Identifier Arguments opt ClassBody opt

于 2013-07-20T17:50:16.747 回答