CGlib使用案例

  实际对象:

1 public class RealObject {
2     public void doSomething() {
3         System.out.println("RealObject.doSomething()");
4     }
5 }

      CGlib代理:

 1 /**
 2  * CGlib代理
 3  * 
 4  * @author Arts&Crafts
 5  * 要让CGlibProxyFactory这个类的对象作为代理的话,必须实现MethodInterceptor
 6  */
 7 public class CglibProxy implements MethodInterceptor {
 8     private Object proxied;
 9 
10     public CglibProxy(Object proxied) {
11         this.proxied = proxied;// 被代理的对象
12     }
13 
14     /**
15      * 当代理对象的业务方法被调用的时候 
16      * proxy  代理对象本身 
17      * method 被拦截的方法 
18      * args 方法的参数 
19      * methodProxy 方法的代理对象
20      */
21     public Object intercept(Object proxy, Method method, Object[] args,
22             MethodProxy methodProxy) throws Throwable {
23         Object result = method.invoke(proxied, args);// 调用被委托的方法
24         System.out.println("cglib动态代理");
25         System.out.println("代理类:" + proxy.getClass().getSimpleName());
26         System.out.println(methodProxy.getClass().getSimpleName());
27         return result;
28     }
29 }

     CGlib代理工厂:

 1 /**
 2  * CGlib代理工厂
 3  * 
 4  * @author Arts&Crafts
 5  * 
 6  */
 7 public class CglibProxyFactory {
 8     public static Object newProxyInstance(Object target) {
 9         // 利用CGLIB.jar组件生成动态代理对象
10         Enhancer hancer = new Enhancer();
11         // 指定代理对象的父类
12         hancer.setSuperclass(target.getClass());
13         // 代理对象
14         CglibProxy cglibProxy = new CglibProxy(target);
15         // 指定回调函数
16         hancer.setCallback(cglibProxy);
17         return hancer.create();
18     }
19 }

    测试类:

 1 public class TestCglib {
 2     @Test
 3     public void test1() {
 4         //原来的对象
 5         RealObject r = new RealObject();
 6         //使用原来的对象生成代理
 7         RealObject ro = (RealObject) CglibProxyFactory.newProxyInstance(r);
 8         ro.doSomething();
 9     }
10 }
原文地址:https://www.cnblogs.com/ArtsCrafts/p/cglib.html