Java 反射允許執行期檢查類別結構、動態建立實例、調用方法、存取欄位,即使類別在編譯期不可見。典型應用場景:
效能提醒:反射比直接調用慢 10-100 倍,高頻熱路徑應避免或緩存 Method/Field 物件。
| 類別 | 核心功能 |
|---|---|
| Class<T> | 類別元資料入口,獲取建構子、方法、欄位、註解等 |
| Constructor<T> | 建構子操作,支援私有建構子存取 |
| Method | 方法操作,含參數型別、回傳型別、異常、註解 |
| Field | 欄位操作,含型別、修飾符、值讀寫 |
| Modifier | 修飾符解析工具(public、static、final 等) |
主程式需動態載入第三方模組 com.example.plugin.Processor,調用其 process(String) 方法,無需編譯期依賴。
public class ReflectionEngine {
private static final Logger LOG = LoggerFactory.getLogger(ReflectionEngine.class);
public String executePlugin(String className, String methodName, String input) {
try {
// 1. 動態載入類別
Class> clazz = Class.forName(className);
// 2. 建立實例(無參建構子)
Object instance = clazz.getDeclaredConstructor().newInstance();
// 3. 獲取目標方法(支援私有方法)
Method method = clazz.getDeclaredMethod(methodName, String.class);
// 4. 破壞封裝(慎用!僅信任代碼)
method.setAccessible(true);
// 5. 調用方法並獲取結果
Object result = method.invoke(instance, input);
return (result != null) ? result.toString() : "null";
} catch (ClassNotFoundException e) {
throw new PluginException("類別不存在: " + className, e);
} catch (NoSuchMethodException e) {
throw new PluginException("方法不存在: " + methodName, e);
} catch (InvocationTargetException e) {
throw new PluginException("方法執行異常", e.getCause());
} catch (ReflectiveOperationException e) {
throw new PluginException("反射操作失敗", e);
}
}
}
// 使用範例
public class Main {
public static void main(String[] args) {
ReflectionEngine engine = new ReflectionEngine();
String result = engine.executePlugin(
"com.example.plugin.TextProcessor",
"toUpperCase",
"hello reflection"
);
System.out.println("結果: " + result); // 輸出: HELLO REFLECTION
}
}
package com.example.plugin;
public class TextProcessor {
public String toUpperCase(String text) {
return text.toUpperCase();
}
// 私有方法也可被反射調用
private String internalProcess(String data) {
return "[PROCESSED] " + data.trim();
}
}
Class.forName(name):預設初始化類別(執行 static 區塊),使用呼叫者的 ClassLoader。ClassLoader.loadClass(name):僅載入不初始化,需指定 ClassLoader,適合模組隔離場景。| 方法 | 範圍 | 繼承鏈 | 可見性 |
|---|---|---|---|
| getMethod() | public 方法 | 包含父類 | 僅 public |
| getDeclaredMethod() | 所有宣告方法 | 僅當前類 | 全部(含 private) |