Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch statement using class.getSimpleName() gives Constant express required error

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;
 }
like image 709
fahmy Avatar asked Dec 20 '14 12:12

fahmy


People also ask

How do you solve a constant error required in Java?

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.

Can switch statements use expressions in Java?

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.

Can we use constants in switch case?

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.

How do you define a constant expression in Java?

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.


1 Answers

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.

like image 57
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet