What is the difference between Integer.class
, Integer.TYPE
and int.class
?
acc to me
Integer.class
is a reference of Integer (Wrapper) Class object- but what is then
int.class
asint
is not a class, it's a primitive type. And what doesInteger.TYPE
refer to?
In plain terms :
EDIT :
So, basically, both return an int. Integer.TYPE just returns the primitive type of the Integer class. It is true for any wrapper class
Java handles primitive types versus class types in a schizophrenic way by defining two types for each primitive.
For instance
int
is the primitive type andInteger
the class type. When you use generics, you are forced to use a non-primitive type soArrayList<Integer>
is allowed butArrayList<int>
not.Since you sometimes want to perform reflection, this duality results in two classes (how else can you inspect a method
public int foo ();
).Say you have a class:
The two methods will not always return the same value, since
value2()
can returnnull
andvalue1()
will throw a runtime error.From
java.lang.Class.isPrimitive
APIThere are nine predefined Class objects to represent the eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double.
These objects may only be accessed via the following public static final variables
java.lang.Boolean.TYPE
,java.lang.Integer.TYPE
etcInteger.class
is, as you say, a reference to theClass
object for theInteger
type.int.class
is, similarity, a reference to theClass
object for theint
type. You're right that this doesn't sound right; the primitives all have aClass
object as a special case. It's useful for reflection, if you want to tell the difference betweenfoo(Integer value)
andfoo(int value)
.Integer.TYPE
(notInteger.type
, mind you) is just a shortcut forint.class
.You can get a sense of this with a simple program:
Example output (it'll be different each time, but the first two will always be the same, and the third will virtually always be different):