In Java, is it possible to use a method/constructor's parameter as a switch statement, case constant?
In a switch case, I've noticed that when I try to use a parameter as a case constant, I get a compilation error. But I can use fields/local vars.
Is it really impossible to use a parameter as a case constant? Or are there exceptions (if so, please provide an example)?
Example:
final int field = 0;
void method( final int parameter) {
switch( 3) {
case field: // ALLOWED
case parameter; // NOT ALLOWED
}
}
I'm trying to use the parameter开发者_JS百科 directly. I'm not interested in solutions that save the value of the parameter in a local var.
Much like C and C++, Java only allows compile-time constants as a value for case
.
The value of initialised final
class members can be determined at compile time and cannot change. final
method parameters can have a different value at each method call.
To compare with method parameters, you probably have to fall back on good-old if...else...
.
EDIT:
By the way, note the emphasis on initialised above. A final
class member without an initialiser at the declaration cannot be used in as a case
value either.
java can use only constants in the case
part
精彩评论