Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write a JDK dynamic proxy that logs the duration of every call to any interface, and describe the pitfalls.

We create the proxy with Proxy.newProxyInstance(loader, new Class<?>[] { iface }, handler), where the InvocationHandler records the start time, calls method.invoke(target, args), logs the duration in a finally block and returns the result. The handler must unwrap InvocationTargetException and rethrow its cause, so callers see the original exception, and it must decide what to do with equals, hashCode and toString, which also go through it. JDK proxies only work for interfaces and add reflection overhead, which is why frameworks often generate bytecode instead.

Background to this question

Writing a dynamic proxy is a classic exercise because it opens the hood on how frameworks add behaviour such as transactions, metrics and remote calls to our code. The code is short, but it has several sharp edges that separate a working answer from a correct one: exceptions that arrive wrapped, Object methods that are intercepted too, and primitive return types. In this answer, we will recap what a JDK dynamic proxy is, write a timing proxy step by step, see the exception pitfall in action, handle equals, hashCode and toString, and then discuss the limits and costs.

1A Quick Recap of JDK Dynamic Proxies

java.lang.reflect.Proxy can generate, at run time, a class that implements one or more interfaces. Every method call on an instance of that class is passed to a single InvocationHandler, an interface with one method: invoke(Object proxy, Method method, Object[] args). The handler decides what happens; usually it does some work and then calls the same method on a real object, the target, using reflection.

So one handler class can add behaviour to any interface without us writing a wrapper class per interface. That is what makes it dynamic.

2Writing the Timing Proxy

Here is a generic factory method that wraps any target in a proxy that logs how long each call takes.

Java
public final class Timing {
private static final System.Logger LOG = System.getLogger("timing");
@SuppressWarnings("unchecked")
public static <T> T timed(Class<T> iface, T target) {
if (!iface.isInterface()) throw new IllegalArgumentException(iface + " is not an interface");
InvocationHandler handler = (proxy, method, args) -> {
long start = System.nanoTime();
try {
return method.invoke(target, args); // call the real object
} catch (InvocationTargetException e) {
throw e.getCause(); // rethrow what the target really threw
} finally {
long micros = (System.nanoTime() - start) / 1_000;
LOG.log(System.Logger.Level.INFO, "{0}.{1} took {2} us",
iface.getSimpleName(), method.getName(), micros);
}
};
return (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface }, handler);
}
}
PriceService prices = Timing.timed(PriceService.class, new RemotePriceService());
prices.price("A-1"); // log: PriceService.price took 18234 us

Let us go through the choices. We use System.nanoTime(), not currentTimeMillis(), because nanoTime is meant for measuring elapsed time and is not affected by clock adjustments. The log line is in a finally block so the duration is recorded whether the call returns or throws; failed calls are often the slow ones we most want to see. We pass the interface's class loader so the generated class can see the interface. And the cast to T is safe because the proxy implements exactly iface.

3The Exception Pitfall: InvocationTargetException

Method.invoke() does not let the target's exception through as it is. It wraps it in an InvocationTargetException. If the handler simply let that propagate, callers would receive something they never expected.

Java
// Without unwrapping: the handler rethrows InvocationTargetException as it is
try {
prices.price("missing");
} catch (ProductNotFoundException e) {
// never reached
} catch (UndeclaredThrowableException e) {
System.out.println(e.getCause().getClass().getSimpleName()); // InvocationTargetException
}
// With throw e.getCause() as above:
try {
prices.price("missing");
} catch (ProductNotFoundException e) {
System.out.println("caught " + e.getMessage()); // caught missing
}
Step throughA failing call through the timing proxy
CallerProxyHandlerTarget
price("missing")
invoke(proxy, method, args)
method.invoke(target, args)
throws ProductNotFoundException, wrapped in InvocationTargetException
finally: log the duration
throw e.getCause(): the caller sees ProductNotFoundException

6 messages in order. Play them, or step through them one at a time.

Notice the second wrapper in the broken case. InvocationTargetException is a checked exception that PriceService.price() does not declare, and when a handler throws a checked exception the interface method does not declare, the proxy wraps it again in UndeclaredThrowableException. So callers catching ProductNotFoundException miss it entirely. Unwrapping with e.getCause() restores the original exception, which is a runtime exception or one the interface declares, so the proxy passes it through unchanged.

4Equals, hashCode and toString Go Through the Handler Too

The proxy also sends the Object methods equals(), hashCode() and toString() to the handler. With our handler, they are forwarded to the target and timed, which has two odd effects: every debugger display or log statement that calls toString() produces a timing line, and proxy.equals(proxy) calls target.equals(proxy), which is usually false, so a proxy is not equal to itself and may misbehave in a HashSet.

Java
InvocationHandler handler = (proxy, method, args) -> {
if (method.getDeclaringClass() == Object.class) {
return switch (method.getName()) {
case "equals" -> proxy == args[0]; // identity of the proxy
case "hashCode" -> System.identityHashCode(proxy);
case "toString" -> "Timed(" + target + ")";
default -> method.invoke(target, args);
};
}
long start = System.nanoTime();
// ... timing as before
};
Set<PriceService> set = new HashSet<>(List.of(prices));
set.contains(prices); // true

We decide explicitly: equality is the identity of the proxy, and toString() describes the wrapper without being timed. Other choices are valid, but they must be choices.

5Limits and Costs

JDK proxies only work for interfaces. A class without an interface, or a method that is not on the interface, cannot be intercepted, which is why Spring falls back to generated subclasses. There are smaller pitfalls too. If an interface method returns a primitive such as int and the handler returns null, the proxy throws NullPointerException. Default methods on the interface also go to the handler; forwarding them to the target works, and InvocationHandler.invokeDefault(), added in Java 16, can call the default implementation directly when there is no target.

Every call also pays for reflection: boxing arguments into an Object array, the reflective invoke and the handler itself. Modern JVMs make reflective calls fairly fast, but it is still slower than a direct call, which matters in hot paths called millions of times. That is one reason frameworks such as Spring and Hibernate, and libraries such as Byte Buddy, often generate bytecode for a real class that calls the target directly. For build-time and native image setups, interfaces that are proxied must also be registered ahead of time, so proxy creation becomes part of the build configuration.

6Follow-up questions

Why not use a decorator class instead?

For one interface, a hand-written decorator is simpler, faster and checked by the compiler. A dynamic proxy pays off when the same behaviour must apply to many interfaces, such as timing every repository or client in a code base, without writing a wrapper for each.

What is the proxy argument in invoke() for?

It is the proxy instance itself. Calling a method on it from inside the handler would call the handler again and recurse, so we use it only for identity, as in our equals, or to return it from fluent methods.

How would you test the proxy?

Wrap a fake implementation, call a method that returns, one that throws a runtime exception and one that throws a declared checked exception, and assert that results and exception types are unchanged. Then check that equals and hashCode behave as decided, for example by putting the proxy in a HashSet.

7Conclusion

In this answer, we wrote a JDK dynamic proxy that times every call. Proxy.newProxyInstance with the interface's class loader and an InvocationHandler creates it; the handler records nanoTime, calls method.invoke on the target, and logs the duration in finally. We saw why InvocationTargetException must be unwrapped, decided how equals, hashCode and toString behave, and looked at the limits: interfaces only, primitive return types, and reflection overhead, which is why frameworks often generate bytecode instead.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd write a generic method that takes the interface class and the target and returns Proxy.newProxyInstance with the interface's class loader, a one-element array with the interface, and an InvocationHandler.

Then, if they want more

In invoke I take System.nanoTime, call method.invoke on the target with the args, return the result, and log the elapsed time in a finally block, so failures are timed too.

The biggest pitfall is exceptions: Method.invoke wraps whatever the target throws in InvocationTargetException, and since that's a checked exception the interface doesn't declare, the proxy would wrap it again in UndeclaredThrowableException. So I catch InvocationTargetException and rethrow getCause, and callers see the original exception.

The second pitfall is that equals, hashCode and toString also go through the handler, so I handle Object methods explicitly, for example identity for equals and hashCode and a descriptive toString that isn't timed; otherwise a proxy isn't even equal to itself.

Others are returning null for a primitive return type, which gives a NullPointerException, and default methods, where invokeDefault since Java 16 helps. And the limits: JDK proxies only work on interfaces and every call goes through reflection and boxing, which is why Spring and Hibernate often generate bytecode subclasses instead.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a JDK dynamic proxy that logs the duration of every call to any interface, and...": https://scrivio-interview-library.netlify.app/java/structural-patterns/7f1297bb3f/