Primitive classes in Java

292 views Asked by At

What is the use of classes like int.class or double.class

For example you can not do something like

    Object val=getValue();
    if(val instanceof int){

    }

or

int i = new int();

Yes I know it is not possible because int is not Object type. However, what is the need to have those primitive classes? I do not see any clear explanation of this in Oracle documentation.

2

There are 2 answers

1
Nicholas Daley-Okoye On BEST ANSWER

It can be useful for reflection.

For example if you wanted to use Class.getDeclaredMethod to lookup a method that took an int as a parameter, you might do something like:

//Find the method foo(int)
Method theMethod = theClass.getDeclaredMethod("foo", int.class);
0
Srini On

In Java, X.class is the syntax for class literals. When X is the name of a class or an interface, the expression X.class evaluates to the Class object representing that class or interface type (which are reference types).

Since there are also Class objects for primitive types (used in reflection as noted by Nicholas), for consistency, they extended the syntax so that for a primitive type X, the expression X.class also evaluates to the Class object representing that primitive type.

#Note: For all primitive types, this value is also available as the static field TYPE of the corresponding wrapper class. So int.class is equivalent to Integer.TYPE.