为什么Integer.class.isInstance(i)在int.class.isInstance(i)和Integer.TYPE.isInstance(i)返回false时返回true?

Bir*_*dra 2 java

Integer.class,int.class和Integer.TYPE有什么区别?我对这三者感到困惑.

rge*_*man 6

无论iintInteger:

  • Integer.class.isInstance(i) 回报 true
  • int.class.isInstance(i) 回报 false
  • Integer.TYPE.isInstance(i) 回报 false

我们明白了isInstance.

public boolean isInstance(Object obj)

确定指定的Object是否与此Class表示的对象分配兼容.

它需要一个Object参数,而不是一个原始类型.int传入的任何内容都将被装箱,Integer因此可以将其传递给方法.

Integer.class是一个类文字,并与引用类型一起使用,它是Class对该类对象的引用.

Integer此方法看到的对象当然是Integer类的实例,因此Integer.class.isInstance(i)返回true.

然而,int.classInteger.TYPE每个代表int原始类型,而不是Integer阶级,一个Integer是不是int,尽管Java的通常使用它们互换,由于装箱和拆箱的事实.这解释了和的两个false输出.int.class.isInstance(i)Integer.TYPE.isInstance(i)

班级文字史

根据Javadocs的Integer说法,Integer.TYPE自1.1版以来一直存在.

自1.1以来,类文字也一直存在.

当类文字语法可用时,需要类对象作为方法参数的Java API更容易使用.

类文字使得使用反射变得非常容易,这在Java 1.1中也是新的.

目前尚不清楚为什么Integer.TYPE存在与参考类文字一致地int.class表示int原始类型.它们在比较它们时是等效的并且==产量true.

  • @Birendra - 首先,请注意`int.class == Integer.TYPE`.它们是同一个对象.其次,`int.class`(或`Integer.TYPE`)在处理反射时很有用."Class"的几种方法期望作为参数的`Class`对象表示构造函数或方法的参数类型.当参数是`int`时,则`int.class`(或`Integer.TYPE`)用于表示该参数.最后,`Integer.class`表示作为`Integer`实例的对象类(不是原始`int`值). (2认同)
  • @Birendra - 我不确定作者为什么这么说.也许他被"Integer.TYPE"类型误导为"Class <Integer>".[docs](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#TYPE)清楚地说'Integer.TYPE`是_"`Class`实例代表原始类型`int`."_.编写一个程序来测试它很容易:`int.class == Integer.TYPE`将是'true`; 对于任何`Integer`变量`i`,`i.getClass()== Integer.class`将为`true`; `Integer.class == Integer.TYPE`将是'false`.此外,`Integer.TYPE.isPrimitive()`将返回`true`. (2认同)