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 is passed as a parameter //for example, if the variable is a string, 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:
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?).
Use getClass(). getSimpleName() to Check the Type of a Variable in Java. We can check the type of a variable in Java by calling getClass(). getSimpleName() method via the variable.
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
If we are given a variable in Java, we can print it by using the print() method, the println() method, and the printf() method.
Type is the common superinterface for all types in the Java programming language. These include raw types, parameterized types, array types, type variables and primitive types.
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 full.package.name.of.Cat
System.out.println(theVariable.getClass());
Read the javadoc.
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