Reflection and dynamic compiling are used to achieve dynamic proxy pattern. Based on learning today, long story in short, there are four steps to implement it.
Get the instance which is the dynamic proxy object.
Implement InvocationHandler interface, and customize the invoke method in it.
public interface InvocationHandler { Object invoke(Object proxy, Method method, Object[] args) throws Throwable; }
InvocationHandler interface is very simple, Reflection can be used inside invoke() method and a callback would be made to this function.
Use Proxy.newInstance() method to generate the dynamic proxy.
ProxyObject obj = (ProxyObject) Proxy.newProxyInstance(MyInterface.class.getClassLoader(), new Class[] { MyInterface.class }, handler);
Where the parameters, first the ClassLoader that is to "load" the dynamic proxy class, second an array of interfaces to implement, and last An InvocationHandler to forward all methods calls on the proxy to.
Call the inner method in the proxy.
An example are the following:
Class SimpleProxy implements invocationHandler { private Object target; public Object newInstance(Object target) { this.target = target; return Proxy.newProxyInstance(target.getClass().getLoader(), target.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) { System.out.print("This is the proxy"); // ... Object res = method.invoke(target, args) return res; } }
And a brief utilization would be the following:
public static void main(String[] args) { SimpleProxy simpleProxy = new SimpleProxy(); // ProxyObjectimpl is the implemented class of interface ProxyObject ProxyObject target = new ProxyObjectimpl(); ProxyObject proxy = (ProxyObject) simpleProxy.newInstance(target); // call is a method in ProxyObject proxy.call(); }
Here are some good reference to talk in detail about Proxy Pattern, a good description of how Proxy.newInstance() works to achieve proxy function, and a self-implemented java.land.reflect.Proxy.
But this implementation only works with interface, since interface checking is implemented in Proxy.newProxyInstance(). If want to do a dynamic proxy in class, CGLIB is the tool to make the proxy for non-final class.
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/66297.html
摘要:代理模式基本概念不論是靜態代理還是動態代理其本質都是代理模式的一種實現那么什么是代理模式呢代理模式即給某一個對象提供一個代理并由代理對象控制對原對象的引用代理模式其實取材于實際生活例如我們生活中常見的房屋租賃代理我們在租房時一般不是直接和房 代理模式 基本概念 不論是靜態代理還是動態代理, 其本質都是代理模式的一種實現, 那么什么是代理模式呢?代理模式, 即給某一個對象提供一個代理, ...
摘要:第二種是,是一款字節碼引擎工具,能夠在運行時編譯生成。后記該部分相關的源碼解析地址該文章講解了遠程調用中關于代理的部分,關鍵部分在于基于實現的字節碼技術來支撐動態代理。 遠程調用——Proxy 目標:介紹遠程調用代理的設計和實現,介紹dubbo-rpc-api中的各種proxy包的源碼。 前言 首先聲明叫做代理,代理在很多領域都存在,最形象的就是現在朋友圈的微商代理,廠家委托代理幫他們...
閱讀 3244·2021-11-18 10:02
閱讀 1947·2021-09-22 10:54
閱讀 2993·2019-08-30 15:43
閱讀 2579·2019-08-30 13:22
閱讀 1580·2019-08-29 13:57
閱讀 1049·2019-08-29 13:27
閱讀 739·2019-08-26 14:05
閱讀 2528·2019-08-26 13:30