In Java, is it possible to print the type of a variable?
public static void printVariableType(Object theVariable){
//print the type of the variable that
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
public static void printVariableType(Object theVariable){
System.out.println(theVariable.getClass())
}
System.out.println(theVariable.getClass());
Read the javadoc.
variable.getClass().getName();
Object#getClass()
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
You can use the ".getClass()"
method.
System.out.println(variable.getClass());
You can read in the class, and then get it's name.
Class objClass = obj.getClass();
System.out.println("Type: " + objClass.getName());