關于動態(tài)代理的那些事 (JDK的動態(tài)代理)有3個接口,分別為ProxyInter1,ProxyInter2,ProxyInter3,但是接口2繼承接口3public?interface?ProxyInter1{
void?func();
}public?interface?ProxyInter2?extends?ProxyInter3{
void?run();
}public?interface?ProxyInter3?{
void?sun();
}下面這個是被代理的類,實現(xiàn)了ProxyInter1,ProxyInter2兩個接口public?class?ProxyImp?implements?ProxyInter1,ProxyInter2{
@Override
public?void?func()?{
System.out.println("This?is?function");
}
@Override
public?void?run()?{
System.out.println("This?is?run");
}
@Override
public?void?sun()?{
System.out.println("This?is?sun");
}
}下面這個是代理的類的執(zhí)行:public?class?MyProxy?{
????public?static?void?main(String[]?args)?throws?Exception?{
ProxyInter1?proxyInter1?=?new?ProxyImp();
ProxyInter2?proxyInter2?=?new?ProxyImp();
ProxyInter3?proxyInter3?=?new?ProxyImp();
ProxyInter3?pInter?=?(ProxyInter3)?Proxy.newProxyInstance
(proxyInter1.getClass().getClassLoader(),?proxyInter1.getClass().getInterfaces(),new?InvocationHandler(){
@Override
public?Object?invoke(Object?proxy,?Method?method,?Object[]?args)?throws?Throwable?{
System.out.println("這是代理之前的事情");
Object?object?=?method.invoke(proxyInter1,args);
System.out.println("這是代理之后的事情");
return?object;
????}
});
// pInter.func();
pInter.sun();
????}
}我的疑問是:1、ProxyInter1,ProxyInter3只是兩個接口,沒有任何關系,invoke方法里面?zhèn)鞯膮?shù)為proxyInter1對象,但是上面Proxy.newProxyInstance返回類型為什么是ProxyInter3的類型,卻不是ProxyInter1類型的,而且調用的方法只能是ProxyInter3的方法,不能調用ProxyInter1的,2、在Proxy.newProxyInstance方法中,按常理說,調用被代理類的類加載器,被代理類的接口(Interfaces),但是,里面寫上proxyInter1,proxyInter2,proxyInter3的三種任意一個都不會報錯,問題是ProxyInter1 和ProxyInter2個接口沒有任何關系,運行出來一樣不會報錯,這是什么原因?麻煩各位大佬幫我解答下,讓我這個小白漲漲知識。。。。。
請教請教,路過的也看一看,幫一幫我,出點主意
有一種放棄叫三分熱情
2017-09-08 12:05:40