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;
}
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.
See more on this question at Stackoverflow