How does this Java statement compile without warnings?
Class<Integer> x = int.class;
even though
Integer.class != int.class
Edit: Putting it a different way, it seems as though Integer.class
and int.class
have nothing in common (see comments below), so why does it make sense for this assignment to be possible?
After a whole lot of searching, I came across this little snippet in the JLS, section 15.8.2 Class Literals:
If p is the name of a primitive type, let B be the type of an expression of type p after boxing conversion (§5.1.7). Then the type of p.class is Class<B>.
The spec doesn't explain why this is so, instead of Class<?>
for example. I have also been unable to find any evidence that this is related to either generics or autoboxing.
Integer
is a first-class object whereas int
is a primitive type, and most methods of Class
such as isInstance
, isAssignableFrom
and cast
which operate on Object
s are invalid in the context of int.class
. Consequently, I do not see any reason why the type of int.class
is Class<Integer>
.
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