Integer.class 和 Integer.TYPE 代表**兩個完全不同的 Class 對象**:
java.lang.Integer 包裝類的 Class<Integer> 對象。int 的 Class<Integer> 對象(即 int.class)。| 特性 | Integer.class (包裝類) | Integer.TYPE / int.class (基本類型) |
|---|---|---|
| 對應類型 | 引用類型 | 基本類型 |
| 堆上分配 | 是 (new Integer() 或自動裝箱) | 否 (棧上/寄存器/對象頭內部) |
| 默認值 | null | 0 |
| 可為 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 // 無方法,不可實例化
int 的 Class 表示,JVM 內建,不可實例化,用於反射識別參數/返回類型。java.lang.Integer 的 Class 表示,可實例化,擁有豐富方法,泛型實參類型。NoSuchMethodException、IllegalArgumentException 等難以排查的錯誤。