The compiler error already says it. The case labels must be constant expressions and neither, class literals nor the result of invoking getSimpleName()
on them, are constant expressions.
A working solution would be:
String tableName = "MyClass1";
...
switch (tableName) {
case "MyClass1":
return 1;
case "MyClass2":
return 2;
default:
return Integer.MAX_VALUE;
}
The expression MyClass1.class.getSimpleName()
is not simpler than "MyClass1"
, but, of course, there won’t be any compile-time check whether the names match existing classes and refactoring tools or obfuscators don’t notice the relationship between the class MyClass1
and the string literal "MyClass1"
.
There is no solution to that. The only thing you can do to reduce the problem, is to declare the keys within the associated class to document a relationship, e.g.
class MyClass1 {
static final String IDENTIFIER = "MyClass1";
...
}
class MyClass2 {
static final String IDENTIFIER = "MyClass2";
...
}
...
String tableName = MyClass1.IDENTIFIER;
...
switch (tableName) {
case MyClass1.IDENTIFIER:
return 1;
case MyClass2.IDENTIFIER:
return 2;
default:
return Integer.MAX_VALUE;
}
This documents the relationship to the reader, but tools still won’t ensure that the actual string contents matches the class name. However, depending on what you want to achieve, it might become irrelevant now, whether the string contents matches the class name…