Java Dynamic Proxy

February 18, 2012

A Basic proxy entails an surrogate object that is inserted between client object and real target object to add more functionality or extra operations or access control. A proxy typically acts as a intermediary or go-between. They can provide for :
– Synchronization
– Authentication
– Remote Access
– Lazy Initialization
– Logging

This is not to be confused with Decorator which is delegation through composition!

Dynamic proxy takes the idea of a proxy one step further, by both creating the proxy object dynamically and handling calls to the proxied methods dynamically. All calls made on a dynamic proxy are redirected to a single invocation handler, which has the job of discovering what the call is and deciding what to do about it.
Code artefacts involved:
– java.lang.reflect.InvocationHandler
– invoke() method of InvocationHandler
– java.lang.reflect.Proxy
– Proxy.newProxyInstance() : to create a proxy object, we need to pass a classloader, a list of interfaces the proxy needs to implement and implementation of InvocationHandler.