代理模式(proxy)的一些整理

代理模式,网上有不少例子。最多的也最全的就是介绍的四种代理模式,静态代理,动态代理--invocationhandler(实现了接口的被代理类),动态代理--CGLIB(未实现接口,类不是final),动态代理--编译器提供的API动态建立代理类(未实现接口,类是final)。我这里整理了一下别人资料。下面是动态代理之一的invocationhandler。详细请看:html

https://www.toutiao.com/i6579893201602085379/?tt_from=mobile_qq&utm_campaign=client_share&timestamp=1541029119&app=news_article&utm_source=mobile_qq&iid=47365531296&utm_medium=toutiao_ios&group_id=6579893201602085379java

public class EnginnerProxy implements InvocationHandler {ios

    Object obj;api

    public Object bind(Object obj){oracle

        this.obj = obj;app

        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);ide

    }this

    @Override.net

    public Object invoke(Object proxy, Method method, Object[] args)  throws Throwable{代理

            System.out.println("Enginner writes document");

            Object res = method.invoke(obj, args);

            return res;

    }

}

**********************************************************************************************

动态代理的一个主要类是proxy,API中是这么介绍:Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods(代理提供建立动态代理类和实例的静态方法,而且也是由这些方法建立的全部动态代理类的超类)。

具体参考proxy API:https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html。

proxy 的方法有四个,getInvocationHandler(Object proxy),getProxyClass(ClassLoader loader, Class<?>... interfaces),isProxyClass(Class<?> cl),newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);具体参考上面API。

newProxyInstance使用到最多的,这篇文档讲的很细很全。能够参考:https://blog.csdn.net/yangaiyu/article/details/73827043;

相关文章
相关标签/搜索