• Java实现动态代理的两种方式


    一般而言,动态代理分为两种,一种是JDK反射机制提供的代理,另一种是CGLIB代理。在JDK代理,必须提供接口,而CGLIB则不需要提供接口,在Mybatis里两种动态代理技术都已经使用了,在Mybatis中通常在延迟加载的时候才会用到CGLIB动态代理。

    1.JDK动态代理:

    public interface Rent {
        public void rent();
    }
    public class Landlord implements Rent{
    
        @Override
        public void rent() {
            System.out.println("房东要出租房子了!");
        }
    }
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class Intermediary implements InvocationHandler{
        
        private Object post;
        
        Intermediary(Object post){
            this.post = post;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object invoke = method.invoke(post, args);
            System.out.println("中介:该房源已发布!");
            return invoke;
        }
    }
    import java.lang.reflect.Proxy;
    
    public class Test {
        public static void main(String[] args) {
            Rent rent = new Landlord();
            Intermediary intermediary = new Intermediary(rent);
            Rent rentProxy = (Rent) Proxy.newProxyInstance(rent.getClass().getClassLoader(), rent.getClass().getInterfaces(), intermediary);
            rentProxy.rent();
        }
    }

    2.CGLIB动态代理:

    public class Landlord {
        public void rent(){
            System.out.println("房东要出租房子了!");
        }
    }
    import java.lang.reflect.Method;
    
    import net.sf.cglib.proxy.MethodInterceptor;
    import net.sf.cglib.proxy.MethodProxy;
    
    public class Intermediary implements MethodInterceptor {
    
        @Override
        public Object intercept(Object object, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {
            Object intercept = methodProxy.invokeSuper(object, args);
            System.out.println("中介:该房源已发布!");
            return intercept;
        }
    }
    import net.sf.cglib.proxy.Enhancer;
    
    public class Test {
        public static void main(String[] args) {
            Intermediary intermediary = new Intermediary();
            
            Enhancer enhancer = new Enhancer();  
            enhancer.setSuperclass(Landlord.class);
            enhancer.setCallback(intermediary);
            
            Landlord rentProxy = (Landlord) enhancer.create();
            rentProxy.rent();
        }
    }
  • 相关阅读:
    跨域资源共享 CORS 详解
    Vue.js 与 Laravel 分离
    Laravel 5.4+Vue.js 初体验:Laravel下配置运行Vue.js
    移动端web及app设计尺寸
    另辟蹊径:vue单页面,多路由,前进刷新,后退不刷新
    vue2.0 keep-alive最佳实践
    教你用Cordova打包Vue项目
    oracle_数据处理
    oracle_集合函数
    oaracel 函数_行转列
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/6433018.html
Copyright © 2020-2023  润新知