1. 程式人生 > >Java動態代理代碼快速上手

Java動態代理代碼快速上手

cfb inter main 兩個 eth print eno 沒有 create

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

舉個例子,上大學的時候,很多同學吃午飯的時候都是叫別人帶飯,有一個人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動態代理代碼快速上手