Search code examples
javaswitch-statementjava-8constantsstring-literals

java 8: difference between class.getName() and String literal


I was working on switch case.

If we use class.getName(), then, I am getting error that "case expressions must be constant expressions" as follows:

switch(param.getClass().getName())
    {
        case String.class.getName():
            // to do
            break;
    }

Even if we do following, take string class name in a constant, then also, getting same error:

public static final String PARAM_NAME = String.class.getName();
switch(param.getClass().getName())
    {
        case PARAM_NAME:
            // to do
            break;
    }

But, if I do following, use the string literal "java.lang.String", there is not error:

public static final String PARAM_NAME = "java.lang.String";

Can anybody please explain this, why its not taking first two cases and taking the last one? Thanks in advance.


Solution

  • classObject.getName() is a method call, and the results of method calls are by definition not compile-time constants. A string literal is a compile-time constant.

    Note that while many situations could take a static final reference as a constant for the lifetime of the program, a switch has to have its options hard-coded at compile-time. The value of a case target must be either an enum value or a (compile-time) ConstantExpression.