Force exhaustive switch

Well, you can probably change a setting in your IDE to turn the warning into an error.

In Eclipse, for example, under Window->Preferences->Java->Compiler->Errors/Warnings, you can decide whether Incomplete 'switch' cases on enum should be ignored or produce a warning or an error.

If your switch statement is not on an enum, it doesn't make sense you force all the cases to be specified, as there would be a huge number of cases.


I know this is an old thread but there is a new answer in the latest JDKs:

Switch Expressions must be exhaustive and are available as a preview language feature in JDK 12 and 13.

https://openjdk.java.net/jeps/354

This means you can modify switch statements that require validation to be switch expressions while other switch statements will continue to work as intended.


Since this is an enum, instead of a switch statement, you can use an abstract method; all enum values will have to implement it. For instance:

public enum MyEnum
{
    A {
        @Override public void foo() { /*whatever*/ }
    }
    // etc

    public abstract void foo();
}

Then call yourEnum.foo() when you need it instead of using a switch statement like you currently do.

And not implementing the method is not an option... Compilation will fail.

Tags:

Java

Enums