In java int, float and etc., are primitive types. Wrapper classes are used in case we need to use it with generics. But still the following declaration works in java,
<int.class
is same type as Class<Integer>
as per the specifications.
From Docs:
The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
From JLS 15.8.2:
15.8.2. Class Literals
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
The type of C.class, where C is the name of a class, interface, or array type , is
Class<C>
.The type of p.class, where p is the name of a primitive type, is
Class<B>
, where B is the type of an expression of type p after boxing conversion.The type of void.class is
Class<Void>
.It is a compile-time error if the named type is a type variable or a parameterized type or an array whose element type is a type variable or parameterized type.
It is a compile-time error if the named type does not denote a type that is accessible and in scope at the point where the class literal appears.
A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.
A primitive becoming an Object
For primitives, there are Class objects available as constants named TYPE in the corresponding wrapper classes -- i.e. int.class is changed to java.lang.Integer.TYPE . For other types, the compiler creates a private member variable in the class being compiled to hold the Class object, and generates code to initialize that member using Class.forName() .
Found some discussion
And a nice discussion here and your example also covered in this link.
A few words from there :
how can a Class be a primitive? Let's confuse things a bit more. We can access the Class object representing a defined class by coding, say:
Equation.class // returns the Equation Class object
But, we can also say:
int.class
obtain a Class object whose name is "int". Note we have not sent the getClass() method to an object; we have used the reserved word for a built-in primitive type (int) and, using dot notation, accessed its class "field." And this returns a Class object!
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a `.' and the token class.
represented as Class objects.
So System.out.println(int.class);
will print int
whereas System.out.println(Integer.class);
will print class java.lang.Integer
.