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.
Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable.
The java. lang. Class. isPrimitive() method can determine if the specified object represents a primitive type.
Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.
Data types are divided into two groups: Primitive data types - includes byte , short , int , long , float , double , boolean and char. Non-primitive data types - such as String , Arrays and Classes (you will learn more about these in a later chapter)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With