Dynamic Proxy Pattern Self-Conclusion
文章目录
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
InvocationHandlerinterface, and customize theinvokemethod in it.public interface InvocationHandler { Object invoke(Object proxy, Method method, Object[] args) throws Throwable; }InvocationHandlerinterface is very simple, Reflection can be used insideinvoke()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
ClassLoaderthat is to "load" the dynamic proxy class, second an array of interfaces to implement, and last AnInvocationHandlerto 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.

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论