Switching Java by enumeration does not detect that all cases are covered

I have a question using Enum inside a switch statement in java:

I declare Enum in Java and use a variable of this type in the switch statement, which addresses all the possible cases for enum values. In this 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 can't the compiler detect that this switch will always initialize msg (or throw a NullPointerException because e is null )?

What I would like to achieve is a switch statement that handles all cases, but will lead to a compilation error if the Enum class is expanded in the future, but a new key is not added to the switch.

+5
source share
2 answers

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 as not to get any errors).

Then for another class one could call test with a new value.

+10
source

I don't know the solution that works with switch-statement, but you can use the Enum Mapper project , which provides an annotation handler that will check at compile time that all enum constants are processed. I think this gives the same result that you are asking for.

In addition, it supports reverse search and parity cards.

0
source

All Articles