JAVA#动态代理'札记

public static void main(String[] args) {
        RealSubject realSubject=new RealSubject();//被代理类的对象;
        MyInvocation myInvocation=new MyInvocation();//代理管理类对象;
        Object o=myInvocation.blinf(realSubject);//返回Object类型的代理类对象o;
        Subject sub=(Subject)o;//sub为代理类的对象
        sub.Slam();//转到对MyInvocation的invoke调用
        ////////////////////////////////////////////////
        NikeClothFactory ncf=new NikeClothFactory();
        Clothproduct prxyCloth=(Clothproduct)myInvocation.blinf(ncf);
        prxyCloth.productCloth();
    }
}
interface Subject{//接口
    void Slam();
}
class RealSubject implements Subject{//实现接口
    @Override
    public void Slam() {
        System.out.println("执行被代理类");
    }
}
class MyInvocation implements InvocationHandler{
    Object object;//声明被代理类
    public Object blinf(Object o){//实例化被代理类,返回一个代理类的对象
        this.object=o;
        return Proxy.newProxyInstance(o.getClass().getClassLoader(),o.getClass().getInterfaces(),this);
    }
    @Override//当通过代理类的对象发起对被重写方法的调用时,都会转成对如下invoke的调用
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception{
        Object returnVal=method.invoke(object,args);
        return returnVal;
    }
}
执行被代理类
nike make cloth

猜你喜欢

转载自blog.csdn.net/Iverson941112/article/details/86426901
今日推荐