8

I'm trying to declare an enum in Java and use a variable of that type in a switch statement, where all possible cases for enum constants of that type are covered.

enum MyEnum {
    FOO, 
    BAR
}

private static void test(MyEnum e) {
    String msg;
    switch (e) {
        case FOO:
            msg = "foo";
            break;
        case BAR:
            msg = "bar";
            break;
    }
    System.out.println("Enum is: " + e + " msg is: " + msg); //compiler error
}

Why is the compiler not capable of detecting that this switch will always initialize msg (or throw a NullPointerException because e is null)?

Michael
  • 41,989
  • 11
  • 82
  • 128
dosw
  • 431
  • 2
  • 10
  • 1
    It's possible to create new instances of an enum using some reflection witchery. – user253751 Jul 03 '15 at 12:06
  • @immibis Even if it was possible, the compiler shouldn't necessarily bother about it. – biziclop Jul 03 '15 at 12:09
  • 2
    Most compilers are capable of detecting this, yet the Java Language Specification does not allow them to abort compilation. Instead it only [recommends](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11) a warning about missing switch cases for enum values. – Robin Krahl Jul 03 '15 at 12:10
  • There's no way to enforce at compile time that all cases are covered separately using switch/case. If a value must be returned for all enum constants, you can for example make that value a field of the enum. – biziclop Jul 03 '15 at 12:13

2 Answers2

14

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.

user253751
  • 57,427
  • 7
  • 48
  • 90
0

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.

TmTron
  • 17,012
  • 10
  • 94
  • 142