Print the Type of a Java Variable

Print the Type of a Java Variable

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?).
1

7 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(); 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.

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

System.out.println(variable.getClass());
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.

public static void printVariableType(Object theVariable){
    System.out.println(theVariable.getClass())
}

You can read in the class, and then get it's name.

Class objClass = obj.getClass();  
System.out.println("Type: " + objClass.getName());  
public static void printVariableType(Object theVariable){
    System.out.println(theVariable);        
    System.out.println(theVariable.getClass()); 
    System.out.println(theVariable.getClass().getName());}



   ex- printVariableType("Stackoverflow");
    o/p: class java.lang.String // var.getClass()
         java.lang.String       // var.getClass().getName()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.