Anderson Green
Anderson Green

Reputation: 31810

Print the type name of object held by variable

In Java, is it possible to print the type of value held by variable?

public static void printVariableType(Object theVariable){
    //for example, if passed argument is "abc", 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?).

Upvotes: 37

Views: 120455

Answers (7)

Pshemo
Pshemo

Reputation: 124235

I am assuming that in case of Animal myPet = new Cat(); you want to get Cat not Animal nor myPet.

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

Upvotes: 38

Ashish Mishra
Ashish Mishra

Reputation: 724

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

Upvotes: 0

Achintya Jha
Achintya Jha

Reputation: 12843

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.

Upvotes: 6

MCWhitaker
MCWhitaker

Reputation: 178

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

Class objClass = obj.getClass();  
System.out.println("Type: " + objClass.getName());  

Upvotes: 4

Marcelo Tataje
Marcelo Tataje

Reputation: 3871

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

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

Upvotes: 6

Jakub Zaverka
Jakub Zaverka

Reputation: 8874

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

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691765

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

Read the javadoc.

Upvotes: 17

Related Questions