How to determine the primitive type of a primitive variable?

ashley picture ashley · Sep 11, 2012 · Viewed 44.3k times · Source

Is there a "typeof" like function in Java that returns the type of a primitive data type (PDT) variable or an expression of operands PDTs?

instanceof seems to work for class types only.

Answer

João Silva picture João Silva · Sep 11, 2012

Try the following:

int i = 20;
float f = 20.2f;
System.out.println(((Object)i).getClass().getName());
System.out.println(((Object)f).getClass().getName());

It will print:

java.lang.Integer
java.lang.Float

As for instanceof, you could use its dynamic counterpart Class#isInstance:

Integer.class.isInstance(20);  // true
Integer.class.isInstance(20f); // false
Integer.class.isInstance("s"); // false