Dynamic proxy in Java

October 26, 2017

Proxy your call to the professional, save you some more time

I recently read a great slides talking about Proxy pattern in Java which has confused me for a long time. I’ve always consider it as something like the delegator pattern which is like adding a new layer for a specified class so that clients can do more other things when calling it.

It turns out that there could be more to do with java dynamic proxy. What dynamic proxy in java can do is let all the interface could share the same proxy so that creating so many proxy handlers is not necessary. With the simple proxy pattern however, one need to create different proxy object based on different interfaces.

How does dynamic proxy works in java

This is the pattern of the dynamic proxy. Comparing to the simple proxy, an Invocation handler layer is added.

Simple proxy

With the simple proxy pattern, you should create a proxy class first public static Object newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler ih) throws IllegalArgumentException: Creates a proxy class defined in the specified class loader and which implements the specified interfaces. In addition, creates an instance of the proxy by invoking the one public proxy constructor which sets the associated invocation handler to the specified handler. Returns a reference to the proxy instance.

Summary

So in order to have a Generic proxy class, we need to have a proxy handler which implement the InvocationHandler where we override the invoke() method

Reference

Dynamic Proxies In Java
Dynamic Proxy Classes
Java 动态代理机制分析及扩展,第 1 部分
Decorating with dynamic proxies