情境設計
Camera 介面:定義 takePhoto()。
Camera01、Camera02:實作 Camera,各有像素、變焦等屬性。
Seller:利用反射動態載入類別、列舉欄位/方法、建立實例、呼叫方法。
Customer:主程式,模擬購買流程。
核心代碼
// 介面
public interface Camera { void takePhoto(); }
// 實作
public class Camera01 implements Camera {
private final int pixels = 300;
private final double zoom = 3.5;
public void takePhoto() { System.out.println("Camera01 has taken a photo"); }
}
public class Camera02 implements Camera { ... } // 類似,參數不同
// 顧客端
public class Customer {
public static void main(String[] args) {
Seller seller = new Seller();
seller.getDescription("com.Camera01");
seller.getDescription("com.Camera02");
Camera cam = (Camera) seller.getCamera("com.Camera02");
seller.testFunction(cam, "takePhoto");
}
}
// 賣家:反射核心邏輯
public class Seller {
// 列舉類別欄位與方法
public void getDescription(String type) {
try {
Class> cla = Class.forName(type);
Object obj = cla.newInstance(); // 無參建構子
Field[] fields = cla.getDeclaredFields();
Method[] methods = cla.getDeclaredMethods();
for (Field f : fields) {
f.setAccessible(true);
System.out.println(f + ": " + f.get(obj));
}
for (Method m : methods) System.out.println(m);
} catch (Exception e) { System.out.println("Sorry, no such type"); }
}
// 呼叫無參方法
public void testFunction(Object obj, String methodName) {
try {
Method m = obj.getClass().getMethod(methodName, (Class>[]) null);
m.invoke(obj, (Object[]) null);
} catch (Exception e) { System.out.println("Sorry, no such function"); }
}
// 取得實例
public Object getCamera(String type) {
try { return Class.forName(type).newInstance(); }
catch (Exception e) { return null; }
}
}
輸出結果
The arguments of this Camera is:
private final int com.Camera01.pixels: 300
private final double com.Camera01.zoom: 3.5
The function of this Camera:
public void com.Camera01.takePhoto()
... Camera02 類似 ...
Camera02 has taken a photo
關鍵技術點
Class.forName():運行時動態載入類別。
getDeclaredFields() + setAccessible(true):存取 private 欄位。
getMethod(name, paramTypes) + invoke(obj, args):動態呼叫方法。
- 所有反射操作皆需捕獲
ClassNotFoundException、NoSuchMethodException、IllegalAccessException 等檢查型異常。