Take the 2-minute tour ×

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 and doesn't help.

share|improve this question
Are you looking for a Class that represents int, long and so on? –  dasblinkenlight Sep 11 '12 at 1:23
You can't have a primitive data type without knowing the type of it. It would have to be boxed in to a Number type in order for you not to know it, in which case you can use instanceof. –  Thor84no Sep 11 '12 at 1:25
@Thor84no yeah you can with reflection –  Bohemian Sep 11 '12 at 1:47
@Bohemian I think reflection also uses wrapper classes automatically, though I haven't tested it. –  Thor84no Sep 11 '12 at 1:49
add comment

2 Answers

up vote 7 down vote accepted

Try the following:

int i = 20;
float f = 20.2f;

It will print:


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
share|improve this answer
havent yet tried but this is what i'm looking for. thanks. –  ashley Sep 12 '12 at 15:52
add comment

There's an easy way that doesn't necessitate the implicit boxing, so you won't get confused between primitives and their wrappers. You can't use isInstance for primitive types -- e.g. calling Integer.TYPE.isInstance(5) (Integer.TYPE is equivalent to int.class) will return false as 5 is autoboxed into an Integer before hand.

The easiest way to get what you want (note - it's technically done at compile-time for primitives, but it still requires evaluation of the argument) is via overloading. See my ideone paste.


public static Class<Integer> typeof(final int expr) {
  return Integer.TYPE;

public static Class<Long> typeof(final long expr) {
  return Long.TYPE;


This can be used as follows, for example:

System.out.println(typeof(500 * 3 - 2)); /* int */
System.out.println(typeof(50 % 3L)); /* long */

This relies on the compiler's ability to determine the type of the expression and pick the right overload.

share|improve this answer
add comment

Your Answer


