动态代理

img.png
img_1.png

img_2.png

动态代理的核心在于InvocationHandler两个方法的使用:

  • Proxy.newProxyInstance(Foo.getClass().getClassLoader(), newclass<?>, handler);获取代理对象Foo
  • invoke(Object proxy, Method method, Object[] args)调用对象方法

下面看代码
出租房接口:

public interfaces Rent{
public void rent();
}

房东类:

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东要租房子");
    }
}

动态代理类:

import org.springframework.http.converter.json.GsonBuilderUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//动态代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //private Rent rent;
    private Object rent;

//    public void setRent(Rent rent) {
//        this.rent = rent;
//    }


    public void setRent(Object rent) {
        this.rent = rent;
    }

    //获取代理类
    public Object getProxy(){
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(), this);
    }

    //处理代理实例
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse(); //在调用方法钱前加入自定义方法
        Object result = method.invoke(rent,args);
        fare(); //在调用方法后加入自定义方法
        return result;
    }


    //中介带看房子
    public void seeHouse(){
        System.out.println("中介带看房子");
    }

    //交房租
    public void fare(){
        System.out.println("交房租");
    }
}


租户:

import java.lang.reflect.Proxy;

public class Client {

    public static void main(String[] args) {
        //真实角色
        Host host = new Host();
        //代理角色, 先获取代理类对象
        ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
        //获取代理角色
        proxyInvocationHandler.setRent(host);
        Rent rent = (Rent)proxyInvocationHandler.getProxy();
        rent.rent();


    }
}

程序结果:


img_3.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容