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

Java 動態代理模式深度解析:InvocationHandler 機制

     編輯:Java 相關知識

場景

董事長 (Director) 實作 Merchant 介面,秘書 (Secretary) 代理簽單。

核心介面與類

public interface Merchant { void treat(); }
public class Director implements Merchant {
    public void treat() { System.out.println("董事長請大家吃飯"); }
}
public class Secretary implements InvocationHandler {
    private Director director;
    public Secretary(Director d) { director = d; }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        director.treat();
        System.out.println("由秘書結帳咯!");
        return null;
    }
}

建立代理實例

Merchant proxy = (Merchant) Proxy.newProxyInstance(
    Director.class.getClassLoader(),
    Director.class.getInterfaces(),
    new Secretary(new Director()));
proxy.treat();

輸出

董事長請大家吃飯
由秘書結帳咯!

關鍵點

  • Proxy.newProxyInstance 動態生成實作目標介面的匿名類(如 $Proxy0)。
  • 所有方法呼叫委派給 InvocationHandler.invoke(),實現攔截、增強、記錄等橫切關注點。
  • 代理類載入器、介面陣列、處理器三要素決定代理行為。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved