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.

  1. Get the instance which is the dynamic proxy object.

  2. 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.

  3. 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.

  4. 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.

评论

暂无评论