cglib代理实例

    技术2022-05-19  25

    前言:如果感觉到使用java动态代理,必须要写接口麻烦。想直接使用类的话,就用cglib吧

    目标对象:

    public class Target {          public String execute() {           String message = "----------test()----------";           System.out.println(message);           return message;       }   }

     

    拦截器:

    import net.sf.cglib.proxy.MethodInterceptor;   import net.sf.cglib.proxy.MethodProxy;      import java.lang.reflect.Method;      public class MyMethodInterceptor implements MethodInterceptor {          public Object intercept(Object object, Method method, Object[] args,    MethodProxy methodProxy) throws Throwable {           System.out.println(">>>MethodInterceptor start...");           Object result = methodProxy.invokeSuper(object,args);           System.out.println(">>>MethodInterceptor ending...");           return "hahahh";       }   }

     

    测试类:

    import net.sf.cglib.proxy.Enhancer;      public class TestCglibProxy  {          public static void main(String rags[]){           Target target = new Target();           TestCglibProxy test = new TestCglibProxy();           Target proxyTarget = (Target)test.createProxy(Target.class);           String res=proxyTarget.execute();           System.out.println(res);       }          public Object createProxy(Class targetClass){           Enhancer enhancer = new Enhancer();           enhancer.setSuperclass(targetClass);           enhancer.setCallback(new MyMethodInterceptor());           return enhancer.create();       }   }  

     

    运行结果:

    C:/classes>java -cp .;C:/classes/cglib-nodep-2.1_3.jar TestCglibProxy >>>MethodInterceptor start... ----------test()---------- >>>MethodInterceptor ending... hahahh

     


    最新回复(0)