首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 反射:Integer.class vs Integer.TYPE 的本質區別

     編輯:程式設計綜合問答

核心結論

Integer.class 和 Integer.TYPE 代表**兩個完全不同的 Class 對象**:

  • Integer.class → java.lang.Integer 包裝類的 Class<Integer> 對象。
  • Integer.TYPE → 基本類型 int 的 Class<Integer> 對象(即 int.class)。

內存模型與 JVM 行為

特性Integer.class (包裝類)Integer.TYPE / int.class (基本類型)
對應類型引用類型基本類型
堆上分配是 (new Integer() 或自動裝箱)否 (棧上/寄存器/對象頭內部)
默認值null0
可為 null是否
方法調用支持 (toString, compareTo...)不支持 (需裝箱)
泛型擦除後保留擦除為 Object
Class 對象創建時機類加載時JVM 啟動時預置

代碼驗證

public class ReflectionDemo {
    public static void main(String[] args) {
        System.out.println(Integer.class == Integer.TYPE);           // false
        System.out.println(Integer.TYPE == int.class);               // true
        System.out.println(Integer.class.getName());                 // java.lang.Integer
        System.out.println(Integer.TYPE.getName());                  // int
        System.out.println(Integer.class.isPrimitive());             // false
        System.out.println(Integer.TYPE.isPrimitive());              // true
        
        // 反射獲取字段類型時的實際表現
        Field f1 = Test.class.getDeclaredField("wrapper");
        Field f2 = Test.class.getDeclaredField("primitive");
        System.out.println(f1.getType() == Integer.class);   // true
        System.out.println(f2.getType() == Integer.TYPE);    // true
    }
}
class Test {
    Integer wrapper;
    int primitive;
}

實戰陷阱:反射調用方法/構造器

// 錯誤示範:試圖用 Integer.class 匹配 int 參數
Method m = Target.class.getMethod("setValue", Integer.class); // 找不到 setValue(int)

// 正確做法
Method m1 = Target.class.getMethod("setValue", int.class);        // 匹配基本類型
Method m2 = Target.class.getMethod("setValue", Integer.class);    // 匹配包裝類型
// Java 編譯器會為基本類型生成橋接方法,但反射需精確匹配參數類型

自動裝箱/拆箱的字節碼視角

Integer i = 10;        // 自動裝箱 → Integer.valueOf(10)
int j = i;             // 自動拆箱 → i.intValue()
Integer k = new Integer(10); // 显式new,不走緩存
// 反射中:
Integer.class.getMethod("valueOf", int.class)   // 靜態工廠方法
Integer.TYPE  // 無方法,不可實例化

總結

  • Integer.TYPE == int.class:基本類型 int 的 Class 表示,JVM 內建,不可實例化,用於反射識別參數/返回類型。
  • Integer.class:包裝類 java.lang.Integer 的 Class 表示,可實例化,擁有豐富方法,泛型實參類型。
  • 反射編程中,**嚴格區分兩者**,否則會導致 NoSuchMethodException、IllegalArgumentException 等難以排查的錯誤。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved