Skip to content

Dynamic Proxy in Java

by Vaibhav Aggarwal on February 9th, 2012

Dynamic proxy is a part of the java.lang.reflect package which was added to the JDK in version 1.3. It allows programs to create proxy objects, which can implement one or more known interfaces and dispatch calls to interface methods programmatically using reflection instead of using the built-in virtual method dispatch. It can be used to create a proxy object which implements a list of interfaces specified at runtime. It intercepts method calls and adds functionality dynamically. Difference between dynamic proxy objects and other proxy objects is that dynamic proxy dispatches call to interface methods reflectively instead of relying on virtual method dispatch. This makes dynamic proxy classes lot more re-usable without writing boilerplate code for each implemented interface.

They are particularly useful in the following:

1. Implementing common logging class.
2. Implementing metrics collection class.
3. Implementing access control to certain objects like your database access objects.
4. It is easy to add more methods to the original class without having to modify the proxy class.
5. Lazy loading of expensive objects.
6. Restricting access to the functionality of an object as the caller cannot upcast the object. So you can use this pattern to limit a caller to calling getter methods only which the original object might have setter methods also.

It is also used in remote method invocation to make a remote object appear available locally.

Some nice articles about Dynamic Proxy in java:

http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html
http://userpages.umbc.edu/~tarr/dp/lectures/DynProxies-2pp.pdf
http://www.ibm.com/developerworks/java/library/j-jtp08305/index.html

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS