動(dòng)態(tài)代理,作為實(shí)現(xiàn)AOP的方式之一,已經(jīng)得到廣泛的應(yīng)用.本人看了很多書(shū)關(guān)于動(dòng)態(tài)代理的介紹,基本就是不知所云. 所以最終自己做了一個(gè)例子,才感到有點(diǎn)明白,下面是我的代碼
(注: 說(shuō)明同一個(gè)包里面的類(lèi)的類(lèi)加載器(ClassLoader)是一樣的)
package
?pear;?

??

//
import?org.springframework.aop.Advisor;?

//
import?org.springframework.aop.BeforeAdvice;?
import
?java.lang.reflect.
*
;?

??


interface
?SayInterface
{??????????
//
?被代理接口?
???????
public
?
void
?say();?

???????
public
?
void
?saytwo();?

}
?


class
?Say?
implements
?SayInterface
{????
//
?被代理的類(lèi)?
???????
public
?
void
?say()
{?

??????????????System.out.println(
"
?in?say?
"
);?

???????}
?


???????
public
?
void
?saytwo()
{?

??????????????System.out.println(
"
in?say?2
"
);?

???????}
?

}
?

??


class
?SayHandler?
implements
?InvocationHandler
{?????
//
?
???????
private
?Say?mysay?
=
?
new
?Say();?????????
//
先生成一個(gè)"被代理類(lèi)"的對(duì)象?
???????
public
?Object?invoke(Object?proxy,Method?method,Object[]?args)
throws
?Exception
{?

??????????????System.out.println(
"
Before
"
);????
//
方法調(diào)用之前輸出Before?
???????????method.invoke(mysay,args);?????????
//
原來(lái)方法在這里才真正被調(diào)用?

??????????????
//
method.invoke(saytwo,args);?
??????????????System.out.println(
"
After
"
);??????
//
方法調(diào)用之后輸出After?
??????????????
return
?
null
;?

???????}
?

}
?

??


public
?
class
?Main?
{?


?
/**?*/
/**
??*?
@param
?args
??
*/
?
public
?
static
?
void
?main(String[]?args)?
{
??
//
?TODO?Auto-generated?method?stub
??SayHandler?handler?
=
?
new
?SayHandler();
??SayInterface?si?
=
?(SayInterface)Proxy.newProxyInstance(

????SayInterface.
class
.getClassLoader(),
new
?Class[]
{SayInterface.
class
}
,handler);

/**?*/
/**
??SayInterface?si?=?(SayInterface)Proxy.newProxyInstance(
//???????handler.getClass().getClassLoader(),handler.say.getClass().getInterfaces(),handler);
??//被代理接口的類(lèi)加載器,被加載的類(lèi),和。。。。
????????SayInterface?si?=?(SayInterface)Proxy.newProxyInstance(handler.getClass().getClassLoader(),);???
*/
?
???si.say();
??si.saytwo();
??System.out.println(
"
the?end

.
"
);
?}
?

}