【问题标题】:Why does Integer.class.isInstance(i) return true while int.class.isInstance(i) and Integer.TYPE.isInstance(i) return false?为什么 Integer.class.isInstance(i) 返回 true 而 int.class.isInstance(i) 和 Integer.TYPE.isInstance(i) 返回 false?
【发布时间】:2015-12-13 09:12:25
【问题描述】:

Integer.class、int.class 和 Integer.TYPE 有什么区别?我对这三者有点困惑。

【问题讨论】:

标签: java


【解决方案1】:

iint 还是 Integer

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

让我们了解isInstance

public boolean isInstance(Object obj)

确定指定的对象是否与该类表示的对象分配兼容。

它将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 输出。

类文字历史

根据Javadocs for IntegerInteger.TYPE 从 1.1 版本就已经存在。

但是class literals have also been around since 1.1.

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

类文字使reflection, which was also new in Java 1.1 的使用变得非常容易。

如果int.class 表示与引用类文字一致的int 原始类型,则尚不清楚为什么存在Integer.TYPE。它们是等价的,比较它们时== 产生true

【讨论】:

  • 感谢您的解释。如果我们无法通过调用 int 变量来获取 int.class,那么它有什么用。我在某处读到 Integer.TYPE 为基元的包装类定义了 Class 对象。然后对于包装器 Integer,它应该是 Integer.TYPE。那么 Integer.class 是什么?
  • @Birendra - 首先,请注意int.class == Integer.TYPE。它们是同一个对象。其次,int.class(或Integer.TYPE)在处理反射时很有用。 Class 的几个方法期望 Class 对象作为参数,这些对象表示构造函数或方法的参数类型。当参数是int 时,则使用int.class(或Integer.TYPE)来表示该参数。最后,Integer.class 表示作为Integer 实例的对象类(不是原始int 值)。
  • 也许他们无法下定决心。 int.class 看起来很奇怪;更不用说void.class
  • @Ted Hopp 我正在阅读“Thinking in Java”,作者说 int.class 用于原始类型,而 Integer.TYPE 用于原始包装类型。
  • @Birendra - 我不确定作者为什么会这么说。也许他被Integer.TYPEClass<Integer> 的类型误导了。 docs 清楚地表明Integer.TYPE“代表原始类型intClass 实例。”。编写一个程序来测试这一点很容易:int.class == Integer.TYPE 将是true;对于任何Integer 变量ii.getClass() == Integer.class 将是trueInteger.class == Integer.TYPE 将是 false。此外,Integer.TYPE.isPrimitive() 将返回 true
猜你喜欢
  • 2012-09-02
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 2014-08-25
  • 2015-03-30
  • 1970-01-01
  • 2014-10-24
相关资源
最近更新 更多