Integer.class vs int.class

user3380123 picture user3380123 · Mar 18, 2014 · Viewed 31.4k times · Source

What is the difference between Integer.class, Integer.TYPE and int.class?

acc to me

  1. Integer.class is a reference of Integer (Wrapper) Class object
  2. but what is then int.class as int is not a class, it's a primitive type. And what does Integer.TYPE refer to?

Answer

yshavit picture yshavit · Mar 18, 2014

Integer.class is, as you say, a reference to the Class object for the Integer type.

int.class is, similarity, a reference to the Class object for the int type. You're right that this doesn't sound right; the primitives all have a Class object as a special case. It's useful for reflection, if you want to tell the difference between foo(Integer value) and foo(int value).

Integer.TYPE (not Integer.type, mind you) is just a shortcut for int.class.

You can get a sense of this with a simple program:

public class IntClasses {
  public static void main(String[] args) {
    Class<Integer> a = int.class;
    Class<Integer> b = Integer.TYPE;
    Class<Integer> c = Integer.class;

    System.out.println(System.identityHashCode(a));
    System.out.println(System.identityHashCode(b));
    System.out.println(System.identityHashCode(c));
  }
}

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):

366712642
366712642
1829164700