首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 反射機制實戰(二):以相機購買情境示範動態載入與方法調用

     編輯:Java 相關知識

情境設計

  • 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 等檢查型異常。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved