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

  • 相关阅读:
    python连接redis
    python3进行md5加密
    python操作mysql数据库
    python3操作excle
    memcache与redis的存储类型
    模块
    函数
    json与字典相互转换
    常用的Random函数
    字符串常用方法
  • 原文地址:https://www.cnblogs.com/cishengchongyan/p/8108215.html
Copyright © 2011-2022 走看看