Java动态代理invoke方法自动执行的原因
Java動(dòng)態(tài)代理invoke方法自動(dòng)執(zhí)行的原因
在動(dòng)態(tài)代理中,一般的是先調(diào)用Proxy.newProxyInstance()生成代理對象,然后通過調(diào)用代理對象的對應(yīng)方法來實(shí)現(xiàn)增強(qiáng),這里假設(shè)代理了被代理對象的test()方法。其中增強(qiáng)的邏輯寫在處理器中(InvocationHandler處理器常通過匿名內(nèi)部類創(chuàng)建)。當(dāng)調(diào)用代理對象的test方法時(shí),處理器中的invoke方法會(huì)自動(dòng)執(zhí)行,這一點(diǎn)較難理解。以下嘗試從源碼的角度對動(dòng)態(tài)代理的機(jī)制進(jìn)行簡要分析。
Proxy類中的主體部分:
public class Proxy implements Serializable{//the invocation handler for this proxy instance.protected InvocationHandler h;}/** parameter types of a proxy class constructor */private static final Class<?>[] constructorParams ={ InvocationHandler.class };//構(gòu)造器protected Proxy(InvocationHandler h) { this.h = h;}//該方法返回類型為(com.sun.proxy.$Proxy0)的代理對像public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)//Look up or generate the designated proxy class. Class<?> cl = getProxyClass0(loader, intfs);final Constructor<?> cons = cl.getConstructor(constructorParams);final InvocationHandler ih = h; return cons.newInstance(new Object[]{h}); }$Proxy0類中的主體(代理對象是該類的實(shí)例)
//以下代碼由$Proxy0.class反編譯得到 public final class $Proxy0 extends Proxy implements PorxyInte {private static Method m3; static { m3 = Class.forName("cn.itcast.web.Test.PorxyInte").getMethod("test", new Class[0]); } //構(gòu)造方法。將invocationhandler實(shí)例從代理類賦值到父類public $Proxy0(InvocationHandler invocationhandler){super(invocationhandler);//創(chuàng)建父類對象}//此處可以看出,當(dāng)調(diào)用代理類的test方法,會(huì)執(zhí)行父類對象屬性h的invoke方法,//h即為通過匿名內(nèi)部類創(chuàng)建的處理器對象public final void test() {super.h.invoke(this, m3, null); //這里的this是代理對象,m3為test方法 }通過匿名內(nèi)部類創(chuàng)建處理器(InvocationHandler對象),
即Proxy.newProxyInstance()方法中的第三個(gè)參數(shù)
new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//此處可以寫增強(qiáng)參數(shù)和方法的代碼 Object result = method.invoke(proImp,null);return result;//此處可以寫增強(qiáng)結(jié)果的代碼 }通過以上代碼不難看出,代理對象創(chuàng)建時(shí)也創(chuàng)建了父類對象,并將處理器傳給了父類對象,通過調(diào)用代理對象的test()方法,執(zhí)行了父類對象中處理器的invoke方法。
說明:為了直觀,本文中修改了部分源代碼,若有理解不當(dāng)?shù)牡胤?#xff0c;歡迎批評指正!
更詳細(xì)的分析,可以參考“碼到”的博文:
https://blog.csdn.net/qq_39056197/article/details/102598674
總結(jié)
以上是生活随笔為你收集整理的Java动态代理invoke方法自动执行的原因的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用家谱链记录家族信息
- 下一篇: 计算机科学与技术高校学科评估排名,教育部