Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.class and int.class

Tags:

java

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?

like image 349
casablanca Avatar asked Feb 04 '12 08:02

casablanca


1 Answers

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 Objects are invalid in the context of int.class. Consequently, I do not see any reason why the type of int.class is Class<Integer>.

like image 110
casablanca Avatar answered Oct 31 '22 09:10

casablanca