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.
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66297.html
摘要:代理模式基本概念不论是静态代理还是动态代理其本质都是代理模式的一种实现那么什么是代理模式呢代理模式即给某一个对象提供一个代理并由代理对象控制对原对象的引用代理模式其实取材于实际生活例如我们生活中常见的房屋租赁代理我们在租房时一般不是直接和房 代理模式 基本概念 不论是静态代理还是动态代理, 其本质都是代理模式的一种实现, 那么什么是代理模式呢?代理模式, 即给某一个对象提供一个代理, ...
摘要:第二种是,是一款字节码引擎工具,能够在运行时编译生成。后记该部分相关的源码解析地址该文章讲解了远程调用中关于代理的部分,关键部分在于基于实现的字节码技术来支撑动态代理。 远程调用——Proxy 目标:介绍远程调用代理的设计和实现,介绍dubbo-rpc-api中的各种proxy包的源码。 前言 首先声明叫做代理,代理在很多领域都存在,最形象的就是现在朋友圈的微商代理,厂家委托代理帮他们...
阅读 3220·2021-11-18 10:02
阅读 1908·2021-09-22 10:54
阅读 2972·2019-08-30 15:43
阅读 2560·2019-08-30 13:22
阅读 1556·2019-08-29 13:57
阅读 1013·2019-08-29 13:27
阅读 710·2019-08-26 14:05
阅读 2493·2019-08-26 13:30