Skip to content
Advertisement

Constant expression required in Java switch statement

I have ths piece of code in Java

 final String workFlowKey = getProcessDefinitionKey();
        
        switch (workFlowKey) {
            case WorkflowKey.DOG_WORKFLOW.getKey():
                return "A";
                break;
            default: return null;
        }

but I have this compilation error: Constant expression required

Advertisement

Answer

The error tells you exactly what is wrong.

Case labels must be compile-time constants. This:

case WorkflowKey.DOG_WORKFLOW.getKey():

has a method call, which is not known at compile time (according to the rules for determining what is constant).

Is WorkflowKey an enum type? Then you should just be switching on the enumerated constants:

case DOG_WORKFLOW:

You’ll need a way to get the enum value from the ‘process definition’ instead of the String you’re getting, of course.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement