Is there a way to enforce that you're switching over all defined values of an enum in Java?

James Ko :

Suppose you have an enum with 3 values:

enum Colors { RED, GREEN, BLUE }

You switch over all values of it in some method, thinking you've handled all cases:

switch (colors) {
    case RED: ...
    case GREEN: ...
    case BLUE: ...
}

Then later, you add a new value to the enum:

enum Colors { RED, GREEN, BLUE, YELLOW }

And everything still compiles fine, except you're silently missing a case for YELLOW in the method. Is there a way to raise a compile-time error in such a scenario?


edit: Do not understand why this was marked a dupe of Can I add and remove elements of enumeration at runtime in Java. Since the answer there was "no", that means it should be possible to know at compile-time all values of an enum, and therefore what I'm asking for should be possible for the compiler/some code analysis tool to implement, right?

Ralf Kleberhoff :

That depends on the compiler. The Eclipse IDE built-in compiler can be configured to raise an error in that case.

Windows/Preferences Java Compiler Errors/Warnings "Incomplete 'switch' cases on enum" can be set to "Error".

EDIT:

There even is a sub-option "signal even if 'default' case exists".

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=465380&siteId=1