Dynamic Proxy in Java

Emre Savcı
hashtech
Published in
2 min readDec 3, 2018

In this post I will introduce you proxy pattern, and how you can implement it in java.

Proxy is a widely used design pattern. Some of the use cases are can be listed as

  • Lazy loading in orms (do you ever think how hibernate lazy loading works under the hood)
  • Mocking objects (yeah dynamic proxy is here too)
  • Intercepting method calls dynamically (like logging before and after execution)

I will give you a simple example of how to create proxy object for given type of object using Java’s Proxy api.

We have a class named Test which implements ITest interface.

interface ITest {
int testIt();
}

class Test implements ITest {
public int testIt() {
return 11;
}
}

First we need to create a class which implements InvocationHandler interface.

class DynamicInvocationHandler implements InvocationHandler {

@Override
public Object invoke(Object proxy, Method method, Object[] args) {

if ("testIt".equals(method.getName())) {
return 5;
}

return null;
}
}

And then we can create our proxy object as below:

public class Main {
public static void main(String[] args) {
DynamicInvocationHandler myTestInvocationHandler = new DynamicInvocationHandler();

ITest test = (ITest)Proxy.newProxyInstance(Test.class.getClassLoader(), new Class[] {
ITest.class
}, myTestInvocationHandler);

System.out.println(test.testIt());
}
}

Proxy.newProxyInstance method takes three argument, first is our class loader, second is interface array which implemented by our class and last is invocation handler itself.

When we run the below example it prints 5 as output.

One restriction while using Java’s Proxy api, it only proxies objects which implements at least one interface. We have to give second parameter to it.

With some modifications we can extend this approach to create our dynamic proxy implementation. We can even write our own mocking library.

--

--

Emre Savcı
hashtech

Tech. Lead @Trendyol & Couchbase Ambassador | Go Türkiye, Kubernetes, Istio, CNCF, Scalability. Open Source Contributor.