问题
Consider the following code:
enum MyEnum {
A, B, C;
}
int foo(MyEnum e) {
switch (e) {
case A:
return 1;
case B:
return 2;
case C:
return 3;
}
}
^ error: missing return statement
The compiler does not like this. Contrast this example with:
int bar() {
if (...) {
return 1;
} else {
return 2;
}
}
The issue with the switch could be addressed with a default
case, but you could argue that's unneeded here. All of the enum values are covered in the cases of the switch. Does static analysis of the switch statement know that, with returns in an exhaustive switch, the code block after the switch statement is unreachable?
I tried looking at the language spec, but I didn't see this point clearly addressed.
回答1:
Well, Java does not implement enums natively as other languages like C/C++ or .NET. They are just instances of a (final) class. So in fact your operator ==
compares for reference equality rather than integer values as you might have suggested.
This is the reason, why the switch statement is not complete. The reference might just be null
.
Furthermore you might have defined your own enum class with a public constructor which might create any arbitrary number of instances.
By the way: the by far easiest way to implement your foo
method is
int foo(MyEnum e)
{ return e.ordinal() + 1;
}
But note that .ordinal()
does not return any value associated with your enum constant. It is just the index in order of definition.
来源:https://stackoverflow.com/questions/50607799/static-analysis-of-exhaustive-switch-statements-of-enums