Why is this int switch valid:
public class Foo {
private final static int ONE = 1;
private final static int TWO = 2;
public static void main(String
I had a similar requirement and worked around this problem by switching on the Enums ordinal number instead of switching on the enum itself. This is not very beautiful/intuitive but it works:
public class Foo {
private final static int SRC = 0; // == RetentionPolicy.SOURCE.ordinal();
private final static int RT = 2; // == RetentionPolicy.RUNTIME.ordinal();
static{
if (RT != RetentionPolicy.RUNTIME.ordinal() || SRC != RetentionPolicy.SOURCE.ordinal()) {
throw new IllegalStateException("Incompatible RetentionPolicy.class file");
}
}
public static void main(String[] args) {
RetentionPolicy value = RetentionPolicy.RUNTIME;
switch (value.ordinal()) {
case RT: break;
case SRC: break;
}
}
}
Note that it is of course not possible to declare the constant as e.g.
private final static int SRC = RetentionPolicy.SOURCE.ordinal();
for the same reason one is not able to declare the constant as an Enum in the first place...