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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With