Java switch over an enum does not detect that all cases are covered
I have a question using an Enum inside a switch statement in java:
I declare an Enum in Java and use a variable of that type in a switch statement, where all possible cases for enum values are covered. In the example each case initializes a variable that was not initialized before the switch, but the compiler still gives me an error because javac does not recognize that all possible cases are covered:
public class EnumSwitchTest {
public enum MyEnum {
FOO,
BAR
}
public static void main(String[] args) {
test(MyEnum.FOO);
test(MyEnum.BAR);
}
private static void test(MyEnum e) {
String msg;
switch (e) {
case FOO:
msg = "foo";
break;
case BAR:
msg = "bar";
break;
}
// Why does the compiler think it is possible to reach here
// and msg could still be uninitialized?
System.out.println("Enum is: " + e + " msg is: " + msg);
}
}
Why is the compiler not capable of detecting that this switch will always initialize msg
(or throw a NullPointerException because e
is null
)?
What I would like to achive is a switch statement, that handles all cases but will result in a compile error if the Enum class is extended in the future but no new case is added to the switch.
Imagine if MyEnum
was a separate class. Then it would be possible to recompile the MyEnum
class, and add new values, without recompiling EnumSwitchTest
(so not getting any errors).
Then it would be possible for another class to call test
with the new value.
I don't know a solution that works with a switch-statement, but you can use the Enum Mapper project which provides an an annotation processor which will make sure at compile-time that all enum constants are handled. I guess this gives the same result that you are asking for.
Moreover it supports reverse lookup and paritial mappers.
链接地址: http://www.djcxy.com/p/88662.html