繁体   English   中英

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

[英]Why does Integer.class.isInstance(i) return true while int.class.isInstance(i) and Integer.TYPE.isInstance(i) return false?

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

iint还是Integer

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

让我们了解isInstance

public boolean isInstance(Object obj)

确定指定的Object是否与此类表示的对象赋值兼容。

它使用一个Object作为参数,而不是原始类型。 传入的所有int都将作为Integer装箱,以便可以将其传递给方法。

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

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

但是, int.classInteger.TYPE分别表示int基本类型,而不是Integer类,并且Integer不是int ,尽管事实上由于装箱和装箱,Java通常可以互换使用它们。 这解释了int.class.isInstance(i)Integer.TYPE.isInstance(i)的两个false输出。

类文字历史

根据用于IntegerJavadocs的说法, Integer.TYPE自1.1版以来一直存在。

但是从1.1开始,类文字也一直存在

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

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

目前尚不清楚,如果int.class与引用类文字一致地表示int基本类型,则为什么存在Integer.TYPE 它们是等效的,比较它们时==得出true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM