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();
    }
}

 

posted @ 2017-02-23 13:18  如果屈原会编程  阅读(14403)  评论(1编辑  收藏  举报