基於接口的動態代理
在不改變源碼的情況下對已有代碼進行增強
首先被代理類必須實現至少一個接口
使用java提供的Proxy類的newProxyInstance()方法,此方法有三個參數
被代理類的類加載器,被代理類實現的接口,InvocationHandler內部類
被代理類.getClass().getClassLoader() , 被代理類.getClass().getInterfaces() ,new InvocationHandler(){ }內部類寫增強代碼
public class Client {
public static void main(String[] args) {
ProxyImp proxyImp = new ProxyImp();
/*
* Proxy.newProxyInstance(被代理類的類加載器,被代理類實現的接口,InvocationHandler內部類)
* 被代理類.getClass().getClassLoader() 被代理類.getClass().getInterfaces()
* new InvocationHandler(){ }內部類書寫增強的代碼
* */
IProxy iProxy = (IProxy) Proxy.newProxyInstance(proxyImpl.getClass().getClassLoader(),
proxyImp.getClass().getInterfaces(), new InvocationHandler() {
/*
* 執行被代理類的任何方法都會經過該方法,該方法有攔截作用
* */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
/*
* proxy 代理對象的引用 method 當前執行的方法 args 當前執行的方法所需的參數
* */
Object result = null;
float money = (float) args[0];
if("one".equals(method.getName())){
if(money>10000){
result=method.invoke(iProxy,money);
}
}
if("two".equals(method.getName())){
if(money>50000){
result=method.invoke(iProxy,money);
}
}
return result;
}
});
基於子類的動態代理
基於子類的動態代理
在不改變源碼的情況下對已有代碼的增強
要求:被代理類不能是最終類。不能被final修飾
使用Enhancer的create()方法來創建代理對象
public static void main(String[] args) {
ActorImp actorImp = new ActorImp();
ActorImp cglibActor = (ActorImp)Enhancer.create(actorImp.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//此方法的前三個參數和InvocationHandler一樣,最後一個參數methodProxy是當前執行方法的代理對象
Object result = null;
float money = (float) args[0];
if("basicAct".equals(method.getName())){
if(money>10000){
result=method.invoke(actorImp,money);
}
}
if("dangerAct".equals(method.getName())){
if(money>50000){
result=method.invoke(actorImp,money);
}
}
return result;
}
});
此文章爲我個人的學習筆記總結,自用