This code throws the error
"Constant expression required" ponting to "INTEGER_CLASS_STRING".
It is a final variable, although it is a constant. Why do I get this error?
My code below:
private static final String INTEGER_CLASS_STRING = Integer.class.toString();
private static final String DOUBLE_CLASS_STRING = Double.class.toString();
switch (definition.get(correctKey).getClass().toString()){
case INTEGER_CLASS_STRING: System.out.println();
case DOUBLE_CLASS_STRING: System.out.println();
}
This is not possible with a switch-statement. The switch-statement in Java is more constrained then most people know. What the comments suggest is true - your constants aren't "constant enough". They may be final, but they are being initialized when the program starts. Java requires the switch label to be known at compile time.
The easiest solution would be to use if-else-if and I'd use the class for comparison directly instead of comparing the names character wise:
Class<?> def = definition.get(correctKey).getClass();
if (Integer.class.equals(def)) {
// your code
} else if (Double.class.equals(def)) {
// double code
} else {
// Error, not found
}
If you "need" to use a switch, then you have to define an Enum with your constants and a function mapping your input to an enum constant.
It would be interesting to know what you're trying to achieve, maybe there is another solution entirely.