In Java, is it possible to print the type of value held by variable?
JavaScript
x
public static void printVariableType(Object theVariable){
//for example, if passed argument is "abc", print "String" to the console.
}
One approach to this problem would be to use an if-statement for each variable type, but that would seem redundant, so I’m wondering if there’s a better way to do this:
JavaScript
if(theVariable instanceof String){
System.out.println("String");
}
if(theVariable instanceof Integer){
System.out.println("Integer");
}
// this seems redundant and verbose. Is there a more efficient solution (e. g., using reflection?).
Advertisement
Answer
I am assuming that in case of Animal myPet = new Cat();
you want to get Cat
not Animal
nor myPet
.
To get only name without package part use
JavaScript
String name = theVariable.getClass().getSimpleName(); //to get Cat
otherwise
JavaScript
String name = theVariable.getClass().getName(); //to get full.package.name.of.Cat