溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java動態(tài)代理的用法

發(fā)布時間:2021-06-23 09:23:29 來源:億速云 閱讀:167 作者:chen 欄目:編程語言

這篇文章主要介紹“java動態(tài)代理的用法”,在日常操作中,相信很多人在java動態(tài)代理的用法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java動態(tài)代理的用法”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

java 中動態(tài)代理 :代理對象(中加入增強對象)、目標對象

1. 創(chuàng)建目標類: HelloWordImpl

public interface HelloWord {
    void sayHelloWord();
}



public class HelloWordImpl implements HelloWord{
    @Override
    public void sayHelloWord() {
        System.out.println("HelloWorld!");
    }
}

2. 創(chuàng)建調用處理程序

public class HelloWorkdHandler implements InvocationHandler {
    // 要代理的原始對象
    private Object object;

    public HelloWorkdHandler(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        //調用之前
        doBefore();
        //調用原始對象的方法
        result = method.invoke(object, args);
        //調用之后
        doAfter();
        return result;
    }

    private void doBefore() {
        System.out.println("before method invoke");
    }

    private void doAfter() {
        System.out.println("after method invoke");
    }
}

3. 使用:

  Proxy.newProxyInstance() 有三個參數(shù):  loader 定義代理類的類加載器 ,interfaces : 代理類要實現(xiàn)的接口列表, 指派方法調用的調用處理程序

    public static void main(String[] args) {
        HelloWord helloWord = new HelloWordImpl();
        InvocationHandler handler = new HelloWorkdHandler(helloWord);

        // 創(chuàng)建動態(tài)代理對象 (傳入目標對象和增強對象)
        HelloWord proxy= (HelloWord) Proxy.newProxyInstance(helloWord.getClass().getClassLoader(),helloWord.getClass().getInterfaces(),handler);
        proxy.sayHelloWord();
    }

到此,關于“java動態(tài)代理的用法”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI