Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java switch statements on enums, why am I getting a compilation error when I qualify my values in each case?

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!

like image 575
Uri Avatar asked Jun 08 '09 14:06

Uri


2 Answers

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.

like image 68
laginimaineb Avatar answered Nov 07 '22 06:11

laginimaineb


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.

like image 33
NeilInglis Avatar answered Nov 07 '22 04:11

NeilInglis