动态代理

JDK代理(依赖接口)

public interface LetRoom {
    void zf();
}
public class FangDong01 implements LetRoom {
    @Override
    public void zf() {
        System.out.println("出租房屋01");
    }
}
public class FangDong02 implements LetRoom {
    @Override
    public void zf() {
        System.out.println("出租房屋02");
    }
}
/**
 * 动态产生代理对象
 */
public class MyInv implements InvocationHandler {

    private LetRoom letRoom;

    public MyInv(LetRoom letRoom) {
        this.letRoom = letRoom;
    }

    public Object getProxy(){
       return Proxy.newProxyInstance(MyInv.class.getClassLoader(),new Class[]{LetRoom.class},this);
    }

    //这个方法就是给用户的租房方法
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("--收取介绍费500元--");

        //调用房东的租房方法
        Object invoke = method.invoke(letRoom, args);

        System.out.println("--收取差价800元--");
        return invoke;
    }
}
public class Test01 {

    public static void main(String[] args) {

        MyInv myInv = new MyInv(new FangDong02());

        //返回的是动态产生的代理(中介)对象
        LetRoom proxy = (LetRoom) myInv.getProxy();

        //调用中介的租房方法
        proxy.zf();

    }
}

 

 

CGLIB代理

public class FangDong03 {
    public void zf(){
        System.out.println("出租房屋03");
    }
}
public class MyIntp implements MethodInterceptor {

    public Object getProxy(){

        Enhancer en=new Enhancer();

        //设置代理对象的父类
        en.setSuperclass(FangDong03.class);

        en.setCallback(this);

        Object o = en.create();

        return o;
    }

    /**
     * @param method:被代理对象中的方法
     * @param methodProxy:代理对象中的方法
     */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("--收取介绍费500元--");

        Object o1 = methodProxy.invokeSuper(o, objects);

        System.out.println("--收取差价800元--");

        return o1;
    }
}
public class Test02 {
    public static void main(String[] args) {

        MyIntp myIntp=new MyIntp();

        FangDong03 proxy = (FangDong01) myIntp.getProxy();

        proxy.zf();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值