动态代理-cglib

实现方法拦截器

 1 package cn.learn.proxy.cglib;
 2 
 3 import net.sf.cglib.proxy.MethodInterceptor;
 4 import net.sf.cglib.proxy.MethodProxy;
 5 
 6 import java.lang.reflect.Method;
 7 
 8 /**
 9  * 实现方法拦截器
10  */
11 public class MyProxy implements MethodInterceptor {
12     /**
13      *
14      * @param o cglib生成的代理对象
15      * @param method 被代理对象的方法
16      * @param objects     传入方法的参数
17      * @param methodProxy 代理的方法
18      * @return
19      * @throws Throwable
20      */
21     public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
22         System.out.println("调用目标方法前,增强.");
23         Object o1 = methodProxy.invokeSuper(o, objects);//关键代码:
24         System.out.println("调用目标方法后,增强.");
25         return o1;
26     }
27 }

设置目标类、方法拦截器

 1 package cn.learn.proxy.cglib;
 2 
 3 import net.sf.cglib.core.DebuggingClassWriter;
 4 import net.sf.cglib.proxy.Enhancer;
 5 
 6 public class CglibDemo {
 7     public static void main(String[] args) {
 8         // 代理类class文件存入本地磁盘方便我们反编译查看源码
 9         System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\code");
10 
11         Enhancer enhancer = new Enhancer();
12         enhancer.setSuperclass(User.class); // 设置目标类
13         enhancer.setCallback(new MyProxy()); // 设置回调为方法拦截器
14         User user = (User) enhancer.create();   // 创建代理对象
15         String world = user.say("world");  // 通过代理对象调用目标方法
16         System.out.println(world);
17     }
18 }

 

posted @ 2022-07-31 11:23  wonkju  阅读(20)  评论(0编辑  收藏  举报