Print the type of a Java variable

Based on your example it looks like you want to get type of value held by variable, not declared type of variable. So I am assuming that in case of Animal animal = new Cat("Tom"); you want to get Cat not Animal.

To get only name without package part use

String name = theVariable.getClass().getSimpleName() //to get Cat

otherwise

String name = theVariable.getClass().getName(); //to get your.package.Cat

System.out.println(theVariable.getClass());

Read the javadoc.


You can use the ".getClass()" method.

System.out.println(variable.getClass());

Tags:

Java