How to determine the primitive type of a primitive variable?
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
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.