34

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?).
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • This question has a deceptively similar title to this one, but appears to be mostly irrelevant: http://stackoverflow.com/questions/6614066/how-can-i-print-out-the-type-size-and-range-of-a-java-data-type-esp-those-wti – Anderson Green Apr 02 '13 at 17:32

7 Answers7

36

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
Pshemo
  • 122,468
  • 25
  • 185
  • 269
16
System.out.println(theVariable.getClass());

Read the javadoc.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
6

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

System.out.println(variable.getClass());
Femaref
  • 60,705
  • 7
  • 138
  • 176
Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51
6
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.

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
4
public static void printVariableType(Object theVariable){
    System.out.println(theVariable.getClass())
}
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
4

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

Class objClass = obj.getClass();  
System.out.println("Type: " + objClass.getName());  
MCWhitaker
  • 178
  • 6
0
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()
Ashish Mishra
  • 704
  • 1
  • 6
  • 20