zoukankan      html  css  js  c++  java
  • cglib动态代理举例

    jdk的动态代理是基于接口的代理,而cglib不要求实现接口,是一种基于继承的代理,使用字节码生成被代理类的子类

    public class TestMethodInterceptor implements MethodInterceptor {
    
        private Object targetObject;
    
        public TestMethodInterceptor(Object target){
            this.targetObject = target;
        }
    
        public Object getProxyInstance() {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(targetObject.getClass());
            enhancer.setCallback(this);
            Object proxy = enhancer.create();
            return proxy;
        }
    
        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("intercept begin");
            System.out.println("class:" + o.getClass().getName() + ", method:"+ method.getName());
            System.out.println("class:" + methodProxy.getClass().getName() + ", method:"+ method.getName());
            methodProxy.invokeSuper(o,objects);
            method.invoke(targetObject,objects);
            System.out.println("intercept end");
            return null;
        }
    
    }
        public static void main(String[] args) {
            SayImpl sayProxy = (SayImpl)new TestMethodInterceptor(new SayImpl()).getProxyInstance();
            sayProxy.sayHello("my dear");
        }

    执行结果:

    intercept begin
    class:com.cainiao.wmpinbound.refund.job.register.node.SayImpl$$EnhancerByCGLIB$$1e0a054, method:sayHello
    class:org.springframework.cglib.proxy.MethodProxy, method:sayHello
    hello:my dear
    hello:my dear
    intercept end

  • 相关阅读:
    #include
    算法导论 Chapter 9.3 Selection in worstcase linear time
    算法导论 Exercises 9.36
    算法导论 Exercises 9.37
    C++实现Ping
    算法导论 Exercises 9.39
    如何计算毫秒级的时间差
    如何产生 [0, 2147483647] 之间的随机数
    算法导论 Exercises 9.38
    KMP算法学习&总结
  • 原文地址:https://www.cnblogs.com/cishengchongyan/p/8108215.html
Copyright © 2011-2022 走看看