What is the difference between Integer.class, int.class and Integer.TYPE? I am kind of confused between the three.
-
2Integer.TYPE and int.class are the same.Louis Wasserman– Louis Wasserman2015-09-16 16:56:52 +00:00Commented Sep 16, 2015 at 16:56
-
1possible duplicate of What is the difference between Integer and int in Java?Caleb Brinkman– Caleb Brinkman2015-09-16 17:09:09 +00:00Commented Sep 16, 2015 at 17:09
1 Answer
Whether i is an int or an Integer:
Integer.class.isInstance(i)returnstrueint.class.isInstance(i)returnsfalseInteger.TYPE.isInstance(i)returnsfalse
Let's understand isInstance.
public boolean isInstance(Object obj)Determines if the specified Object is assignment-compatible with the object represented by this Class.
It takes an Object as an argument, not a primitive type. Any int passed in will be boxed as an Integer so it can be passed to the method.
Integer.class is a class literal, and used with a reference type, that is a reference to the Class object for that class.
The Integer object that this method sees certainly is an instance of the Integer class, so Integer.class.isInstance(i) returns true.
However, int.class and Integer.TYPE each represent the int primitive type, not the Integer class, and an Integer is not an int, despite the fact that Java usually uses them interchangeably, due to boxing and unboxing. This explains the two false outputs from int.class.isInstance(i) and Integer.TYPE.isInstance(i).
Class literal history
According to the Javadocs for Integer, Integer.TYPE has been around since version 1.1.
But class literals have also been around since 1.1.
Java APIs which require class objects as method arguments are much easier to use when the class literal syntax is available.
The class literals made it tremendously easier to use reflection, which was also new in Java 1.1.
It is unclear why Integer.TYPE exists if int.class represents the int primitive type consistently with reference class literals. They are equivalent and == yields true when comparing them.
6 Comments
int.class == Integer.TYPE. They are the same object. Second, int.class (or Integer.TYPE) is useful when dealing with reflection. Several methods of Class expect as arguments the Class objects representing the types of the arguments to constructors or methods. When the argument is an int, then int.class (or Integer.TYPE) is used to represent that argument. Finally, Integer.class represents the class of objects that are instances of Integer (not primitive int values).int.class does look odd; not to mention void.classInteger.TYPE being Class<Integer>. The docs clearly say that Integer.TYPE is "The Class instance representing the primitive type int.". It is easy enough to write a program to test this: int.class == Integer.TYPE will be true; i.getClass() == Integer.class will be true for any Integer variable i; Integer.class == Integer.TYPE will be false. Also, Integer.TYPE.isPrimitive() will return true.