這篇文章將為大家詳細(xì)講解有關(guān)深入淺析java 1.8 中動(dòng)態(tài)代理的原理,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
JDK8動(dòng)態(tài)代理源碼分析
動(dòng)態(tài)代理的基本使用就不詳細(xì)介紹了:
例子:
class proxyed implements pro{ @Override public void text() { System.err.println("本方法"); } } interface pro { void text(); } public class JavaProxy implements InvocationHandler { private Object source; public JavaProxy(Object source) { super(); this.source = source; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); Object invoke = method.invoke(source, args); System.out.println("after"); return invoke; } public Object getProxy(){ return Proxy.newProxyInstance(getClass().getClassLoader(), source.getClass().getInterfaces(), this); } public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException { //第一種,自己寫 //1.設(shè)置saveGeneratedFiles值為true則生成 class字節(jié)碼文件方便分析 System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); //2.獲取動(dòng)態(tài)代理類 Class proxyClazz = Proxy.getProxyClass(pro.class.getClassLoader(),pro.class); //3.獲得代理類的構(gòu)造函數(shù),并傳入?yún)?shù)類型InvocationHandler.class Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class); //4.通過(guò)構(gòu)造函數(shù)來(lái)創(chuàng)建動(dòng)態(tài)代理對(duì)象,將自定義的InvocationHandler實(shí)例傳入 pro iHello = (pro) constructor.newInstance(new JavaProxy(new proxyed())); //5.通過(guò)代理對(duì)象調(diào)用目標(biāo)方法 iHello.text(); //第二種,調(diào)用JDK提供的方法,實(shí)現(xiàn)了2~4步 Proxy.newProxyInstance(JavaProxy.class.getClassLoader(),proxyed.class.getInterfaces(),new JavaProxy(new proxyed())); } }