0

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();
 }
AleksanderGD
  • 414
  • 5
  • 10
SG Tech Edge
  • 477
  • 4
  • 16
  • 2
    A switch statement requires a compile time constant - you are referencing *toString*, which is a function. Have a look at this answer that goes into more detail https://stackoverflow.com/a/3827424/1538039 – Dylan Morley Jun 16 '20 at 15:45
  • I t does not, beacuse the answer there is to make the variable "final", what I already did – SG Tech Edge Jun 16 '20 at 15:55

1 Answers1

1

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.

Benjamin Maurer
  • 3,602
  • 5
  • 28
  • 49