Java動態代理代碼快速上手

來源:互聯網
上載者:User

標籤:java   code   重寫   退出   lun   oca   一個人   tin   ace   

動態代理的兩個核心的點是:代理的行為 和 代理機構。

 

舉個例子,上大學的時候,很多同學吃午飯的時候都是叫別人帶飯,有一個人H特別熱心腸,想了一個辦法,他在門口掛了個公示牌,每天有誰想要找人帶飯就寫公告牌上寫下自己想吃的飯,H每次直接記下誰誰誰想吃什麼飯然後去幫大家買飯。這就是一個典型代理的過程。這裡代理的行為就是帶飯,代理的機構就是H。而且代理行為和代理機構之間進行瞭解耦。

 

下面,我們基於這個例子使用JDK提供的代理機制來實現代碼。

首先,我們建立一個代理行為類介面BuyLunchInt(因為可能會有很多人需要帶飯,並且帶不同的飯,用於繼承實現)

package proxy;/** * @Author darrenqiao */public interface BuyLunchInt {    void buyLunch();}
View Code

 

接著,我們基於代理行為的介面實現代理機構(代理機構的實現是核心)

  • 主要用到兩個reflection包中的兩個類,Invocationhandler 和 Proxy類。
  • Proxy類通過傳入的類資訊建立代理執行個體
  • InvocationHandler則通過實現invoke方法實現代理執行個體方法的執行
package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;/** * @Author darrenqiao * 基於代理的行為介面實現的代理機構類 * 主要工作兩部分: * 通過Proxy建立代理執行個體 * 通過重寫InvocationHandler類的invoke方法實現代理行為的執行 */public class ProxyAgent implements InvocationHandler {    private Object target;    public Object create(Object target) {        this.target = target;        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);    }    //實現代理機制,通過反射基於介面調用方法    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("看看誰要我幫忙帶飯");        method.invoke(target, args);        System.out.println("呐,你的飯");        return null;    }}
View Code

 

然後,就是有哪些人需要帶飯,帶什麼飯,就實現介面BuyLunchInt並寫到公告牌configure.properties中

package proxy;/** * @Author darrenqiao */public class DarrenBuyLunch implements BuyLunchInt {    @Override    public void buyLunch() {        System.out.println("darren要吃炒飯");    }}
View Code
class=proxy.DarrenBuyLunch
View Code

 

最後,在main方法中,幾個步驟,先看看公告牌configure.properties上有麼有需要代理的對象,有則建立代理機構並代理執行;沒有則退出。

import proxy.BuyLunchInt;import proxy.ProxyAgent;import java.io.*;import java.util.Properties;/** * @Author darrenqiao */public class Main {    static Properties prop = new Properties();    static void init(){        try {            //這裡初始化需要代理的類            InputStream inputStream = new BufferedInputStream(new FileInputStream("C:\\zongpengq\\code\\testDynamicProxy\\src\\configure.properties"));            prop.load(inputStream);        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {        init();        if (prop.size() == 0){            System.out.println("今天沒人要帶飯");            return;        }        //建立代理機構        ProxyAgent proxyAgent = new ProxyAgent();        for (String s : prop.stringPropertyNames()) {            String className = prop.getProperty(s);            Class classInfo = Class.forName(className);            //建立具體的代理的對象            BuyLunchInt buyLunch = (BuyLunchInt)classInfo.newInstance();            //代理機構為代理對象建立代理執行個體(類似:給你安排個人代理你去做這件事)            BuyLunchInt proxy = (BuyLunchInt)proxyAgent.create(buyLunch);            //代理去做事            proxy.buyLunch();        }    }}
View Code

 

我們看看啟動並執行結果,如果沒有人需要帶飯(即把公告牌configure.properties清空),運行結果如下

如果有人需要帶飯,比如Darren,在configure.properties中進行了配置,運行結果如下

 

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.