Integer.class与int.class

Integer.classInteger.TYPEint.class什么int.class

适合我

  1. Integer.class是Integer(Wrapper)类对象的引用
  2. 但是int.class是什么,因为int不是一个类,它是一个原始类型。 Integer.TYPE指的是什么?

来自java.lang.Class.isPrimitive API

有九个预定义的Class对象来表示八种基本类型和void。 它们由Java虚拟机创建,并且与它们表示的基本类型具有相同的名称,即boolean,byte,char,short,int,long,float和double。

这些对象只能通过以下公共静态最终变量java.lang.Boolean.TYPEjava.lang.Integer.TYPE等进行访问。

正如你所说, Integer.class是对Integer类型的Class对象的引用。

int.class是, int.class ,对int类型的Class对象的引用。 你是对的,这听起来不对; 基元都有一个Class对象作为特例。 如果你想告诉foo(Integer value)foo(int value)之间的区别,它对于reflection很有用。

Integer.TYPE (不是Integer.type ,请注意)只是int.class的快捷方式。

您可以通过一个简单的程序了解这一点:

 public class IntClasses { public static void main(String[] args) { Class a = int.class; Class b = Integer.TYPE; Class c = Integer.class; System.out.println(System.identityHashCode(a)); System.out.println(System.identityHashCode(b)); System.out.println(System.identityHashCode(c)); } } 

示例输出(每次都会有所不同,但前两个将始终相同,而第三个实际上总是不同):

 366712642 366712642 1829164700 

简单来说:

int – >是原语…用于简单的数学运算。 您无法将它们添加到集合中。

整数 – >对象本身就是整数的包装器。 即,它们可以与集合一起使用(因为它们是对象)。 它们被GC收集为普通对象。

编辑:

 public static void main(String[] args) { int i = 5; System.out.println(int.class); Integer i1 = new Integer(5); System.out.println(Integer.TYPE); } O/P : int int 

所以,基本上,两者都返回一个int。 Integer.TYPE只返回Integer类的基本类型。 对于任何包装类都是如此

Java通过为每个基元定义两种类型,以精神分裂的方式处理基本类型与类类型。

例如, int是基本类型, Integer是类类型。 当您使用generics时,您被迫使用非基本类型,因此允许使用ArrayList但不允许使用ArrayList

由于您有时希望执行reflection,因此这种二元性会产生两个类(如何检查方法public int foo (); )。

假设你有一个class级:

 public class Foo { private Integer value; public int value1 () { return value; } public Integer value2 () { return value; } } 

这两个方法并不总是返回相同的值,因为value2()可以返回nullvalue1()将抛出运行时错误。