Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a JDK dynamic proxy that logs the time taken by every method of any interface implementation. Mention one bug people often make in the handler.

We write an InvocationHandler that holds the real target, records System.nanoTime() before calling method.invoke(target, args), and logs the elapsed time in a finally block so failed calls are timed too. We create the proxy with Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[] { iface }, handler) and cast it to the interface. The classic bugs are calling method.invoke(proxy, args) instead of the target, which recurses forever, and not unwrapping InvocationTargetException, which makes callers see the wrong exception type.

Why this question is asked

Timing every method of a service is a classic first use of dynamic proxies: one small class adds the behaviour to any interface, without touching the implementation or writing a wrapper per method. It is also how frameworks such as Spring add metrics, transactions and security, so writing one by hand shows we understand what they do underneath. Interviewers like this exercise because a version that looks right can still hang the JVM or change exceptions in ways that break callers. In this answer, we will recap how a JDK proxy routes calls, write the timing handler, create and use the proxy, and then look at the two common bugs and why each one happens.

1A Quick Recap of JDK Dynamic Proxies

A JDK dynamic proxy is an object whose class is generated at run time to implement one or more interfaces. We do not write that class; we write an InvocationHandler, an interface with a single method invoke(proxy, method, args). Every call on the proxy, whichever interface method it is, ends up in that one method, with the proxy itself, a Method object describing the method that was called, and the arguments as an Object array, or null when there are none.

So a timing proxy needs only two things: the real object to forward calls to, and code around the forwarding call that measures the time. Because the handler sees every method in the same way, it works for any interface.

2Writing the Timing Handler

Here is the handler, with a small factory method so callers do not have to repeat the Proxy call.

Java
import java.lang.reflect.*;
public final class TimingHandler implements InvocationHandler {
private static final System.Logger LOG = System.getLogger("timing");
private final Object target;
private TimingHandler(Object target) { this.target = target; }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
try {
return method.invoke(target, args); // the real object, never proxy
} catch (InvocationTargetException e) {
throw e.getCause(); // rethrow what the method really threw
} finally {
long micros = (System.nanoTime() - start) / 1_000;
LOG.log(System.Logger.Level.INFO, "{0}.{1} took {2} us",
method.getDeclaringClass().getSimpleName(), method.getName(), micros);
}
}
public static <T> T timed(Class<T> iface, T target) {
Object proxy = Proxy.newProxyInstance(iface.getClassLoader(),
new Class<?>[] { iface }, new TimingHandler(target));
return iface.cast(proxy); // typed, no unchecked cast
}
}
Step throughOne timed call through the proxy
CallerProxyTimingHandlerReal service
priceOf("A-1")
invoke(proxy, priceOf, ["A-1"])
start = nanoTime()
method.invoke(target, args)
1299
finally: log elapsed time
1299

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

Each part has a reason. System.nanoTime() is used instead of currentTimeMillis() because it is a monotonic clock meant for measuring intervals and does not jump when the system clock is adjusted. The finally block runs whether the method returns or throws, so slow failures, often the most interesting ones, are logged too. The catch block unwraps InvocationTargetException, the wrapper reflection puts around any exception thrown by the target, for reasons we will see in a moment. Using iface.cast() checks the type at run time and avoids an unchecked-cast warning.

3Creating and Using the Proxy

Now we wrap a real implementation and call it through the interface. The caller cannot tell that it is talking to a proxy.

Java
interface PriceService {
long priceOf(String sku) throws IOException;
}
class CatalogPriceService implements PriceService {
public long priceOf(String sku) throws IOException {
if (sku.isBlank()) throw new IllegalArgumentException("empty sku");
return 1299; // pretend this called a database
}
}
PriceService prices = TimingHandler.timed(PriceService.class, new CatalogPriceService());
System.out.println(prices.priceOf("A-1")); // 1299
// INFO: PriceService.priceOf took 842 us
prices.priceOf(" ");
// INFO: PriceService.priceOf took 35 us (logged by finally)
// java.lang.IllegalArgumentException: empty sku (the same exception a direct call throws)

Notice that the second call still logged its time, and the caller saw the IllegalArgumentException exactly as it would without the proxy. Calls to toString(), equals() and hashCode() on the proxy also pass through the handler and get forwarded to the target, which is fine for timing, and they will appear in the log as Object methods.

4Bug 1: Invoking the Method on the Proxy

The handler receives two objects, proxy and target, and they are easy to mix up. Here is the mistake.

Java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
try {
return method.invoke(proxy, args); // wrong object
} finally { /* log */ }
}
prices.priceOf("A-1");
// java.lang.StackOverflowError (possibly wrapped in other exceptions)

The reason is that calling a method on the proxy sends the call to the handler again, which calls the proxy again, and so on until the stack runs out. The proxy parameter exists for rare cases such as returning the proxy itself from a fluent method, or comparing identities in equals; for forwarding we always use the stored target.

5Bug 2: Not Unwrapping InvocationTargetException

The second mistake is subtler. Suppose the handler simply lets method.invoke throw.

Java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
try {
return method.invoke(target, args); // no catch for InvocationTargetException
} finally { /* log */ }
}
prices.priceOf(" ");
// java.lang.reflect.UndeclaredThrowableException
// Caused by: java.lang.reflect.InvocationTargetException
// Caused by: java.lang.IllegalArgumentException: empty sku

Here is why. method.invoke wraps the target's IllegalArgumentException in an InvocationTargetException, which is a checked exception. The handler throws it, but priceOf() declares only IOException. A proxy cannot let an undeclared checked exception escape, so it wraps it once more in UndeclaredThrowableException. The caller's catch (IllegalArgumentException e) no longer matches, and an IOException the service declares would also arrive wrapped. Rethrowing e.getCause() restores the original exception, so the proxy is transparent again, which is the whole point of a proxy.

6Follow-up questions

How would you exclude toString, equals and hashCode from the log?

Check method.getDeclaringClass() == Object.class at the start of invoke and forward those calls without timing. It keeps the log focused on the service's real methods, and it is also where we would handle equals specially if proxies of the same target should compare equal.

Is the proxy's own overhead included in the measured time?

Mostly not, because we start the clock inside the handler and stop it right after method.invoke returns. The reflective call itself adds a little, usually well under a microsecond on recent JDKs, which is negligible for a service call but matters for very small methods. For hot code we would measure with a profiler or JMH rather than log every call.

How does Spring do the same thing?

Spring builds the proxy for us, a JDK proxy or a CGLIB subclass, and runs interceptors around each call. A @Timed annotation with Micrometer, or an @Around aspect, gives the same timing without writing InvocationHandler code, and the results go to a metrics registry instead of a log.

7Conclusion

In this answer, we wrote an InvocationHandler that holds the real target, measures each call with System.nanoTime() around method.invoke(target, args), and logs the time in a finally block so failures are timed too. We created the proxy with Proxy.newProxyInstance and the interface's class loader and cast it with iface.cast. We also saw the two common bugs: invoking the method on the proxy instead of the target, which recurses until StackOverflowError, and not unwrapping InvocationTargetException, which makes callers see UndeclaredThrowableException instead of the real exception.

What to say in the interviewAbout 80 seconds aloud

Open with

I'd write a TimingHandler implementing InvocationHandler that keeps a reference to the real target. In invoke, I take System.nanoTime() before calling method.invoke(target, args), and in a finally block I compute the elapsed time and log it with the interface and method name, so calls that throw are timed too.

Then, if they want more

I catch InvocationTargetException and rethrow getCause(). Then a small generic factory creates the proxy with Proxy.newProxyInstance, passing the interface's class loader, an array with the interface, and the handler, and casts the result with iface.cast. Callers use it exactly like the real service. The bug people make most often is calling method.invoke(proxy, args) instead of the target.

The proxy routes that call straight back into the handler, so it recurses until a StackOverflowError. The second common bug is not unwrapping InvocationTargetException. Reflection wraps whatever the target throws, and since that wrapper is a checked exception the interface doesn't declare, the proxy wraps it again in UndeclaredThrowableException, so a caller catching IllegalArgumentException or IOException no longer catches anything.

Rethrowing the cause keeps the proxy transparent. I'd also note that toString, equals and hashCode go through the handler, so I might skip timing for methods declared by Object.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 time taken by every method of any interface...": https://scrivio-interview-library.netlify.app/java/reflection-and-method-handles/cd803c3260/