Is there any way of converting an enum into a constant expression? I want my switch operator to choose among the values of an enum, but I got a compile error "case expressions must be constant expressions", so I tried to declare it in a variable:
final int REG = MyEnum.REG.getIndex().intValue(); switch (service.getIndex()) { case REG: But I still get the same error. According to Oracle's documentation http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
•Literals of primitive type and literals of type String
So it isn't working because I'm not using a literal. I think I will have to declare it as:
final int REG = 8; But it'd be much better to link it to the enum. Is there any way of doing this?
EDIT
Turns out I don't need to use any final variable. It is just as simple as:
switch (service) { case REG: It didn't occur to me till I saw Andrea's comment. Thanks for your answers.
service.getIndex()returnsInteger, right? Can you modify it so that it returns your enum?Stringinswitch-case, but you can use it in Java 7. FYI