I'm trying to use class.getSimpleName() for the expression of a switch however it gives me an error:
Constant express required
I've seen answers suggesting to change the expression variable declarations to have initializers that are compile-time constant expressions. However, this is not possible in this case.
Is there a way to make a switch using class.getSimpleName() without having to hardcode the class names?
Example code
public class ClassA {
public static final String TAG = ClassA.class.getSimpleName();
...
}
public class ClassB {
public static final String TAG = ClassB.class.getSimpleName();
...
}
public class SomeOtherClass {
switch (express) {
case ClassA.TAG: // Error here
...
break;
case ClassB.TAG: // and here
...
break;
default:
...
break;
}
The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions. In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final may be what is needed.
Java SE 12 introduced switch expressions, which (like all expressions) evaluate to a single value, and can be used in statements. It also introduced "arrow case " labels that eliminate the need for break statements to prevent fall through.
The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
A constant expression is an expression that yields a primitive type or a String, and whose value can be evaluated at compile time to a literal. The expression must evaluate without throwing an exception, and it must be composed of only the following: Primitive and String literals.
Is there a way to make a switch using class.getSimpleName() without having to hardcode the class names?
No. Basically, calling Class.getSimpleName()
doesn't count as a compile-time constant expression, so it can't be used as a case statement. It would be nice if there were a nameof(...)
operator as there will be in C# 6, but without that, I don't think you'll be able to use a switch/case without hard-coding the names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With