java cglib代理特性验证

    xiaoxiao2021-04-13  28

    验证cglib 生成代理对象,能不能在方法内部调用的内部方法进行植入逻辑。

    首先编写被代理类

    package test; public class Proxy {     public void a()     {         System.out.println("a");         b();     }          public void b()     {         System.out.println("b");     } }

    编写代理逻辑:

    package test;     import net.sf.cglib.proxy.MethodInterceptor;   import net.sf.cglib.proxy.MethodProxy;   import java.lang.reflect.Method;    public class CglibProxy implements MethodInterceptor {       @Override       public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {           System.out.println(method.getName()+"  start");           Object o1 = methodProxy.invokeSuper(o, args);           System.out.println(method.getName()+"  end");         return o1;       }   }  

    验证代码:

    package test; import net.sf.cglib.proxy.Enhancer; public class test2 {     public static void main(String[] args) {         CglibProxy cglibProxy = new CglibProxy();                    Enhancer enhancer = new Enhancer();           enhancer.setSuperclass(Proxy.class);           enhancer.setCallback(cglibProxy);              Proxy o = (Proxy)enhancer.create();           o.a();          //o.getAge(1);      } }

    输出结果:

    a  start a b  start b b  end a  end

    结论:cglib代理对象可以对内部方法进行植入逻辑

    转载请注明原文地址: https://ju.6miu.com/read-668406.html

    最新回复(0)