Tuesday, September 16, 2014

Dynamic Proxies in Java

Dynamic proxies in Java is a way to provide an implementation to an interface method at runtime. Proxies are used extensively by frameworks like Hibernate to provide behaviors at runtime.

Creating a Proxy 

First let's define an interface for which we will create a Proxy object. Only interfaces can be proxied. IF you want to proxy a class than you will need to use cglib

public interface InterfaceToProxy {

    public void callMe(String arg1, Integer arg2);

The behaviour is provided by a concrete implementation of InvocationHandler interface

public class ProxyBehaviorHandler implements InvocationHandler {

* This method will be called whenever the method on interface is called.
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Entered into proxy method");
                   ("Class of proxy is: " + proxy.getClass().toString());
                    ("Method invoked is: " + method.getName());

for(Object obj:args){
                    ("Argument is of type: " + obj.getClass().toString());
return null;

And the main method, where we will create the proxy. Calling a method on the interface will call the method implemented in the concrete implementation of InvocationHandler

// Create an instance of handler class
ProxyBehaviorHandler proxyBehaviorHandler = new ProxyBehaviorHandler();

// Create a dynamic proxy
InterfaceToProxy interFaceToProxy = (InterfaceToProxy) Proxy
new Class[] { InterfaceToProxy.class },

// Call the method on the proxy. This will result in calling the method
// implemented in handler
interFaceToProxy.callMe("Hello", 2);

// The proxy instance will be true for instance of operator
System.out.println(interFaceToProxy instanceof InterfaceToProxy);

Output of above method:
Entered into proxy method
Class of proxy is: class com.sun.proxy.$Proxy0
Method invoked is: callMe
Argument is of type: class java.lang.String
Argument is of type: class java.lang.Integer

Code at GitHub

No comments:

Post a Comment