專案中某模組擁有上百個分類代碼,每個代碼對應一個處理方法。若使用大量 if-else 或 switch 判斷,程式碼難以維護。利用 Java 反射機制,可根據代碼動態拼裝方法名並呼叫,極大簡化程式結構。
package com.escs.xmlutils;
import java.lang.reflect.Method;
public class Test {
public String ceshi() {
System.out.println("1111111111111");
return "success";
}
public String ceshi(String str) {
System.out.println(str);
return str;
}
public String ceshi2(String str, int i) {
for (int j = 0; j < i; j++) {
System.out.println(str + "22222");
}
return str;
}
public static void main(String[] args) throws Exception {
// 載入類別
Class<?> c = Class.forName("com.escs.xmlutils.Test");
Object obj = c.newInstance();
// 取得方法 (方法名, 參數型別...)
Method method = c.getMethod("ceshi2", String.class, int.class);
// 執行方法並傳遞參數
String result = (String) method.invoke(obj, new Object[]{"myname", 4});
System.out.println(result);
}
}
public String fanShe(String methodName, String className)
throws ClassNotFoundException, SecurityException, NoSuchMethodException,
InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Class<?> c = Class.forName(className);
Object obj = c.newInstance();
// 假設方法簽名固定為 (String, int),實際應根據需求動態決定
Method method = c.getMethod(methodName, String.class, int.class);
String result = (String) method.invoke(obj, new Object[]{"myname", 4});
return result;
}
若代碼為 1~100,方法命名為 ReturnCode1() ~ ReturnCode100(),可直接拼裝方法名呼叫:
String methodName = "ReturnCode" + code; // code 為 1~100 String result = fanShe(methodName, "com.example.Handler");
Method 物件NoSuchMethodException、IllegalAccessException 等)setAccessible(true) 才能存取反射機制讓 Java 擁有動態語言的靈活性,善用它能將大量條件判斷轉化為簡潔的動態路由邏輯,但需權衡效能與可讀性,於適當場景使用。