簡體   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