关于Java动态代理

思想,在不改变原有代码的基础上,对方法进行增强

其实现方式有两种:

一、基于接口的动态代理

对应的参数介绍:actor.getClass().getClassLoader()表示类加载器,和被代理对象使用相同的类加载器,固定写法

        actor.getClass().getInterfaces()表示被代理对象实现的接口,要求被代理对象和代理对象具有相同的行为,固定写法

        InvocationHandler表示要增强的代码,执行任何被代理对象的任何方法都经过此方法,该方法有拦截作用

 1 IActor proxyActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(),
 2 actor.getClass().getInterfaces(), new InvocationHandler() {
 3 
 4 @Override
 5 public Object invoke(Object proxy, Method method, Object[] args)
 6 throws Throwable {
 7 
 8 Object rtValue = null;
 9 //1、取出执行方法中的参数
10 Float money = (Float) args[0];
11 //2、判断当前执行的是什么方法
12 if("basicAct".equals(method.getName())){
13 //基本演出
14 if(money > 10000){
15 //执行方法开始表演
16 rtValue = method.invoke(actor, money);
17 }
18 }
19 if("dengerAct".equals(method.getName())){
20 //基本演出
21 if(money > 50000){
22 //执行方法开始表演
23 rtValue = method.invoke(actor, money);
24 }
25 }
26 return rtValue;
27 }
28 });
View Code

 

二、基于子类的动态代理

需要提供CGLIB的包,要求:被代理类不能是最终类,不能被final修饰

Actor cglibActor = (Actor) Enhancer.create
(actor.getClass(), new MethodInterceptor() {

/**
* 参数介绍:
* proxy:表示代理对象的引用
* method:当前执行的方法
* arg0:当前执行方法的参数
*/
@Override
public Object intercept(Object proxy, Method method, Object[] arg0,
MethodProxy arg3) throws Throwable {

Object rtValue = null;
Float money = (Float) arg0[0];
if("basicAct".equals(method.getName())){
//动态代理添加的条件,演员演出时,经纪公司出面
if(money > 10000){
//开始调用方法,actor为创建对象的引用,money为该方法的参数
rtValue = method.invoke(actor, money/2);
}
}
if("dengerAct".equals(method.getName())){
if(money > 50000){
rtValue = method.invoke(actor, money/2);
}
}

return rtValue;
}
});

 

posted on 2021-01-10 21:32  南瓜小子  阅读(48)  评论(0)    收藏  举报

导航