標籤: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動態代理代碼快速上手