Complete forced switch

Is there an annotation or other way to include a non-exclusive statement error warning in the error message? I want a particular method or class to throw an error if not all values ​​were correctly processed in the switch.

Example:

public enum E { A, B } 

and somewhere else in the code there is a switch on this listing, like so

 switch (enumValue) { case A: /* do something */ break; } 

Java will give you a warning that this switch does not process all enumeration values. I want to turn this warning into an error (constantly, regardless of the individual IDE settings).

Please keep in mind that I cannot change the original enum in this case, so I want the compiler to execute it.

+6
source share
3 answers

Since this is an enumeration, you can use an abstract method instead of a switch statement; all enumeration values ​​will need 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 the switch statement as you are doing now.

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

+3
source

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

In Eclipse, for example, in Window->Preferences->Java->Compiler->Errors/Warnings , you can decide whether to ignore Incomplete 'switch' cases on enum or cause a warning or error.

If your switch statement is not in the enumeration, it makes no sense that you force all cases to be specified, as there would be a huge number of cases.

+2
source

Linters, such as Checkstyle, will note this, so if you make the linter part of your assembly, you will get a β€œcompile time” (I get that this is the phase after compilation, but this is basically the same) warning. There is even a Checkstyle (and probably other linter) integration in Eclipse and IntelliJ, so this is flagged in your IDE.

0
source

Source: https://habr.com/ru/post/978820/


All Articles