基于接口的动态代理
在不改变源码的情况下对已有代码进行增强
首先被代理类必须实现至少一个接口
使用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;
}
});
此文章为我个人的学习笔记总结,自用