Java动态代理代码快速上手
動(dòng)態(tài)代理的兩個(gè)核心的點(diǎn)是:代理的行為 和 代理機(jī)構(gòu)。
?
舉個(gè)例子,上大學(xué)的時(shí)候,很多同學(xué)吃午飯的時(shí)候都是叫別人帶飯,有一個(gè)人H特別熱心腸,想了一個(gè)辦法,他在門口掛了個(gè)公示牌,每天有誰想要找人帶飯就寫公告牌上寫下自己想吃的飯,H每次直接記下誰誰誰想吃什么飯然后去幫大家買飯。這就是一個(gè)典型代理的過程。這里代理的行為就是帶飯,代理的機(jī)構(gòu)就是H。而且代理行為和代理機(jī)構(gòu)之間進(jìn)行了解耦。
?
下面,我們基于這個(gè)例子使用JDK提供的代理機(jī)制來實(shí)現(xiàn)代碼。
首先,我們創(chuàng)建一個(gè)代理行為類接口BuyLunchInt(因?yàn)榭赡軙?huì)有很多人需要帶飯,并且?guī)Р煌娘?#xff0c;用于繼承實(shí)現(xiàn))
package proxy; /*** @Author darrenqiao*/ public interface BuyLunchInt {void buyLunch(); } View Code?
接著,我們基于代理行為的接口實(shí)現(xiàn)代理機(jī)構(gòu)(代理機(jī)構(gòu)的實(shí)現(xiàn)是核心)
- 主要用到兩個(gè)reflection包中的兩個(gè)類,Invocationhandler 和 Proxy類。
- Proxy類通過傳入的類信息創(chuàng)建代理實(shí)例
- InvocationHandler則通過實(shí)現(xiàn)invoke方法實(shí)現(xiàn)代理實(shí)例方法的執(zhí)行
?
然后,就是有哪些人需要帶飯,帶什么飯,就實(shí)現(xiàn)接口BuyLunchInt并寫到公告牌configure.properties中
package proxy; /*** @Author darrenqiao*/public class DarrenBuyLunch implements BuyLunchInt {@Overridepublic void buyLunch() {System.out.println("darren要吃炒飯");} } View Code class=proxy.DarrenBuyLunch View Code?
最后,在main方法中,幾個(gè)步驟,先看看公告牌configure.properties上有么有需要代理的對象,有則創(chuàng)建代理機(jī)構(gòu)并代理執(zhí)行;沒有則退出。
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;}//創(chuàng)建代理機(jī)構(gòu)ProxyAgent proxyAgent = new ProxyAgent();for (String s : prop.stringPropertyNames()) {String className = prop.getProperty(s);Class classInfo = Class.forName(className);//創(chuàng)建具體的代理的對象BuyLunchInt buyLunch = (BuyLunchInt)classInfo.newInstance();//代理機(jī)構(gòu)為代理對象創(chuàng)建代理實(shí)例(類似:給你安排個(gè)人代理你去做這件事)BuyLunchInt proxy = (BuyLunchInt)proxyAgent.create(buyLunch);//代理去做事 proxy.buyLunch();}} } View Code?
我們看看運(yùn)行的結(jié)果,如果沒有人需要帶飯(即把公告牌configure.properties清空),運(yùn)行結(jié)果如下
如果有人需要帶飯,比如Darren,在configure.properties中進(jìn)行了配置,運(yùn)行結(jié)果如下
?
轉(zhuǎn)載于:https://www.cnblogs.com/darrenqiao/p/9270854.html
總結(jié)
以上是生活随笔為你收集整理的Java动态代理代码快速上手的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Class对象和反射
- 下一篇: 巧妙使用网页在线工具,让您的工作更简单