反射調用靜態方法時,Method.invoke(Object obj, Object... args) 的第一個參數 傳入 null 即可,因為靜態方法不依賴實例。
import java.lang.reflect.Method;
public class StaticReflectionDemo {
public static void main(String[] args) throws Exception {
// 1. 獲取 Class 對象
Class> mathClass = Class.forName("java.lang.Math");
// 2. 獲取靜態方法 Method 對象
// 參數:方法名、參數類型陣列
Method absMethod = mathClass.getMethod("abs", long.class);
// 3. 調用靜態方法
// 第一個參數傳 null,後續參數為實際引數
Object result = absMethod.invoke(null, -10000L);
System.out.println("Math.abs(-10000L) = " + result); // 輸出:10000
}
}
| 步驟 | 代碼 | 說明 |
|---|---|---|
| 載入類 | Class.forName("java.lang.Math") | 亦可用 Math.class |
| 獲取方法 | getMethod("abs", long.class) | 僅能獲取 public 方法;私有靜態方法用 getDeclaredMethod + setAccessible(true) |
| 調用執行 | invoke(null, -10000L) | null 代表靜態調用,若為實例方法則傳實例對象 |
long.class vs Long.class,基本類型用 .class,包裝類用 Long.class。InvocationTargetException 真實異常在 getCause() 中。MethodHandle 或緩存 Method 對象。同樣原理適用於調用靜態字段(
Field.get(null))、私有靜態方法(需setAccessible(true))。掌握「第一個參數傳 null」這一核心規則,靜態反射調用即刻上手。