java動態代理

來源:互聯網
上載者:User

標籤:AC   load   []   return   handle   span   targe   row   傳遞   

一介面和實作類別

interface Subject {    public void hello();}class RealSubject implements Subject {    @Override    public void hello() {        System.out.println("hello");    }}

二、建立代理實作類別

class DynamicProxy implements InvocationHandler {    // 代理的真實對象    private Object target;    public DynamicProxy(Object target) {        this.target = target;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("beffor");        // 當代理對象調用真實對象的方法時,其會自動執行代理對象關聯的handler對象的invoke方法來進行調用,        // 無論何時調用代理對象的方法,調用處理器的 invoke 方法都會被調用, 並向其傳遞Method 對象和原始的調用參數。 調用處理器必須給出處理調用的方式         method.invoke(target, args);        System.out.println("affter");        return null;    }}

三、測試代碼

class ProxyTest {    public static void main(String[] args) {        Subject realSubject = new RealSubject();        InvocationHandler invocationHandler = new DynamicProxy(realSubject);                 /*     * 通過Proxy的newProxyInstance方法來建立我們的代理對象,我們來看看其三個參數     * 第一個參數  類載入器 handler.getClass().getClassLoader() ,我們這裡使用realSubject這個類的ClassLoader對象來載入我們的代理對象     * 第二個參數  一個class對象數組,每個元素都要實現的介面。我們這裡為代理對象提供的介面是真實對象所實行的介面,表示我要代理的是該真實對象,這樣我就能調用這組介面中的方法了     * 第三個參數 一個調用處理器 invocationHandler, 我們這裡將這個代理對象關聯到了上方的 InvocationHandler 這個對象上     * */        Subject proxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),                realSubject.getClass().getInterfaces(), invocationHandler);        proxy.hello();        //realSubject.hello();    }}

 

java動態代理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.