Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

java - Why can't an enum value be fully qualified in a switch statement?

(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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

SwitchLabel expects an EnumConstantName, which is defined as the enum constant identifier, which is unqualified:

EnumConstant:
Annotationsopt Identifier Argumentsopt ClassBodyopt


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...