首页 > 代码库 > 动态代理

动态代理

1 客户通过代理类来调用其他对象的方法,并且是在程序运行时根据需要动态创建目标类的代理类对象

package lianxi2;// 静态代理类:代理类和被代理类必须配对,创建的数量如果很多,会很麻烦。interface SellHouse{    void sellHouse();}class HouseProducer implements SellHouse{    @Override    public void sellHouse() {      System.out.println("我是开发商,我要卖房子");            }}class HouseProxy implements SellHouse{    HouseProducer hp;    public HouseProxy(HouseProducer hp) {        super();        this.hp = hp;    }    @Override    public void sellHouse() {         System.out.println("我是中介,我们代理开发商销售房子");         hp.sellHouse();        }    }public class TestHouseProxy {        public static void main(String[] args) {        HouseProducer hp1 = new HouseProducer();        HouseProxy pro1 = new HouseProxy(hp1);        pro1.sellHouse();    }}
package lianxi2;//2.动态代理的使用import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;interface Food{    void sellfood();}class FoodProduce implements Food{    @Override    public void sellfood() {         System.out.println("我是食品生产商,负责提供食品");            }}//代理类class MyinvocationHandler implements InvocationHandler{    Object obj;  //实现接口的被代理类的对象的声明    //1.给被代理类对象实例化 2.返回一个代理类对象    public Object blind(Object obj){          this.obj = obj;        return Proxy.newProxyInstance(this.getClass().getClassLoader(),                 this.getClass().getInterfaces(), this);            }    //当通过代理类的对象发起对被重写的方法调用时,转换为调用invoke方法    @Override    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        Object returnVal = method.invoke(obj, args); //方法返回值returnval        return returnVal;    }    }public class TestDynamicProxy {    public static void main(String[] args) {        FoodProduce fp = new FoodProduce();        MyinvocationHandler mh = new MyinvocationHandler();        //调用builder方法,同样返回一个实现fp所在类实现的Food接口的代理类对象        Object obj = mh.blind(fp);        FoodProduce fp2 = (FoodProduce)obj;        fp2.sellfood();                HouseProducer hp1 = new HouseProducer();        HouseProducer hp2 = (HouseProducer)mh.blind(hp1);        hp2.sellHouse();    }}

动态代理