views:

840

answers:

2

I have a switch statement in Java, on an Enum which let us call IMyInterface.MyEnum

Each of my case statements has the form: IMyInterface.MyEnum.MyValue, (though I could drop the IMyInterface if I imported).

However, the compiler (Java 6) throws an error: "The qualified case label IMyInterface.MyEnum.MyValue must be replaced with the unqalified enum constant MyValue".

I can obviously do that, but for the life of me I don't understand what is the purpose of this error. Clearly, if the compiler can deal with the actual value, it should be able to deal with the fully qualified name just as it would for constants. In fact, I would have assumed that the compiler turns the constant into the fully qualified name.

So, Java gurus, what's the rationale behind this? Thank you!

+1  A: 

That's an odd one. I had to do some digging myself to find out about this. It seems that it's safer to type check on the object being switched on than in the full qualified name.

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6191812 was a bug report raised to allow you to specify qualified enums but it was closed and not actioned for the reasons you can see in the enclosure.

NeilInglis
+11  A: 

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.)

You can find it here.

laginimaineb
How did you ever find that bit? +1 for finding a needle in a haystack.
Michael Myers
lol I recalled reading something about this once... Luckily I have the JLS PDF on my desktop just for these kind of occasions ;)
laginimaineb
I have it favorited (so all I have to do is open a new tab and type JLS), but I still couldn't find anything relevant. I guess I didn't think of binary compatibility as a possible reason.
Michael Myers
My God...+1 (and props) for minutiae.
Jared