zoukankan      html  css  js  c++  java
  • 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();
        }
    }
  • 相关阅读:
    Java JMX 监管
    Spring Boot REST(一)核心接口
    JSR 规范目录
    【平衡树】宠物收养所 HNOI 2004
    【树型DP】叶子的颜色 OUROJ 1698
    【匈牙利匹配】无题II HDU2236
    【贪心】Communication System POJ 1018
    【贪心】Moving Tables POJ 1083
    Calling Extraterrestrial Intelligence Again POJ 1411
    【贪心】Allowance POJ 3040
  • 原文地址:https://www.cnblogs.com/lxcmyf/p/6433018.html
Copyright © 2011-2022 走看看