Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the type of a Java variable

Tags:

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?). 
like image 593
Anderson Green Avatar asked Apr 02 '13 17:04

Anderson Green


People also ask

How do you find the type of a variable in Java?

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.

How do you print a type of 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.

How do you print a variable in Java?

If we are given a variable in Java, we can print it by using the print() method, the println() method, and the printf() method.

What is type () in Java?

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.


2 Answers

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 
like image 66
Pshemo Avatar answered Oct 27 '22 04:10

Pshemo


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

Read the javadoc.

like image 23
JB Nizet Avatar answered Oct 27 '22 04:10

JB Nizet