Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 566
Krishna Kumar Avatar asked Nov 11 '15 08:11

Krishna Kumar


People also ask

What is getClass () getName () in Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.

What is getName method in Java?

File getName() method in Java with Examples The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.

What is the difference between getClass and. class in Java?

getClass() method can't help us to get the Class object of a primitive type. So, we can obtain the Class object of the int primitive type through int. class. In Java version 9 and later, a Class object of primitive type belongs to the java.

How do you call a class name in Java?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.


1 Answers

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.

like image 195
chrylis -cautiouslyoptimistic- Avatar answered Oct 17 '22 05:10

chrylis -cautiouslyoptimistic-