Sub topic 13
Dynamic proxies with InvocationHandler
This chapter assumes you know the Method class and Method.invoke, how checked exceptions work, and how to write a Java interface and a lambda. It builds on the previous chapters about invoking methods and unwrapping InvocationTargetException.
What a dynamic proxy is
A dynamic proxy is an object that the JVM builds at runtime to implement one or more interfaces you name. You don't write its class. Every call on the proxy goes to a single method, InvocationHandler.invoke, and your code decides what happens next.
The proxy can forward the call to a real object, return a made-up result, or refuse the call. This is how many frameworks add logging, transactions, security checks, and remote calls without changing the classes involved.
The API has two parts:
java.lang.reflect.Proxy.newProxyInstance(ClassLoader, Class<?>[], InvocationHandler)creates the proxy object.java.lang.reflect.InvocationHandleris an interface with one method:Object invoke(Object proxy, Method method, Object[] args) throws Throwable.
A first proxy
This example has no real implementation behind the interface. The handler is the implementation.
import java.lang.reflect.Proxy;
interface Greeter {
String greet(String name);
}
public class ProxyDemo {
public static void main(String[] args) {
Greeter g = (Greeter) Proxy.newProxyInstance(
Greeter.class.getClassLoader(),
new Class<?>[] { Greeter.class },
(proxy, method, methodArgs) -> {
System.out.println("calling " + method.getName());
return "Hello, " + methodArgs[0];
});
System.out.println(g.greet("Ada"));
}
}It prints calling greet, then Hello, Ada.
The three arguments to newProxyInstance mean this:
- The class loader that defines the generated proxy class. Using the interface's own loader is the usual choice.
- The interfaces the proxy implements. Only interfaces are allowed. A proxy cannot stand in for a concrete class.
- The handler that receives every call.
The cast to Greeter is safe because the proxy class implements every interface you listed.
How a call travels
The proxy class is generated by the JVM. Each interface method in it is a stub that packages the Method object and the arguments and calls your handler.
The proxy parameter of invoke is the proxy object itself, not the target. Calling a method on proxy inside the handler calls the handler again, which usually ends in a StackOverflowError. Use it only for identity checks or to return it from a method that returns this.
Wrapping a real object
The most common pattern is a decorator. The handler holds a real object, adds behavior around the call, and forwards it. The example below times each call.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Calculator {
int add(int a, int b);
int divide(int a, int b);
}
class RealCalculator implements Calculator {
public int add(int a, int b) { return a + b; }
public int divide(int a, int b) { return a / b; }
}
class TimingHandler implements InvocationHandler {
private final Object target;
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);
} catch (InvocationTargetException e) {
throw e.getCause();
} finally {
long micros = (System.nanoTime() - start) / 1000;
System.out.println(method.getName() + " took " + micros + " us");
}
}
}
public class TimingDemo {
@SuppressWarnings("unchecked")
static <T> T wrap(T target, Class<T> iface) {
return (T) Proxy.newProxyInstance(
iface.getClassLoader(),
new Class<?>[] { iface },
new TimingHandler(target));
}
public static void main(String[] args) {
Calculator calc = wrap(new RealCalculator(), Calculator.class);
System.out.println(calc.add(2, 3));
try {
calc.divide(1, 0);
} catch (ArithmeticException e) {
System.out.println("caught " + e.getMessage());
}
}
}The wrap helper keeps the cast in one place. The caller sees only the Calculator interface and cannot tell it holds a proxy.
The catch (InvocationTargetException e) block matters. Method.invoke wraps whatever the target throws. If the handler let that wrapper escape, the caller would see a confusing exception instead of the ArithmeticException it expects. Throwing e.getCause() restores the original exception, as you did in the earlier chapter on invoking methods. The finally block runs on both the success and failure paths, so the timing is printed either way.
Edge cases and gotchas
| Situation | What happens | What to do |
|---|---|---|
| `args` for a method with no parameters | `args` is `null`, not an empty array | Check for `null` before indexing |
| Handler returns `null` for a method returning `int`, `boolean`, or another primitive | The proxy throws `NullPointerException` | Return a boxed value of the right type, such as `Integer.valueOf(0)` |
| Handler returns a value of the wrong type | The proxy throws `ClassCastException` | Match the method's declared return type |
| Handler throws a checked exception the interface method does not declare | The proxy wraps it in `UndeclaredThrowableException` | Throw only declared checked exceptions, or unchecked ones |
| Handler throws an unchecked exception or a declared checked exception | The caller receives it unchanged | Nothing extra |
| `toString()`, `hashCode()`, or `equals()` on the proxy | These three methods are routed to the handler | Handle `Object` methods explicitly |
| Interface has a `default` method | The call still goes to the handler | Forward it with `InvocationHandler.invokeDefault` (Java 16+) |
The Object methods catch many people. The first example's handler reads methodArgs[0] for every call. If you print the proxy with System.out.println(g), the JVM calls toString(), args is null, and the handler fails with a NullPointerException. A more careful handler checks the method first:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Counter {
int next();
}
public class ObjectMethodsDemo {
public static void main(String[] args) {
int[] state = { 0 };
InvocationHandler handler = (proxy, method, methodArgs) -> {
if (method.getDeclaringClass() == Object.class) {
switch (method.getName()) {
case "toString": return "CounterProxy";
case "hashCode": return System.identityHashCode(proxy);
case "equals": return proxy == methodArgs[0];
default: throw new UnsupportedOperationException(method.getName());
}
}
return ++state[0];
};
Counter c = (Counter) Proxy.newProxyInstance(
Counter.class.getClassLoader(), new Class<?>[] { Counter.class }, handler);
System.out.println(c);
System.out.println(c.next() + " " + c.next());
System.out.println(c.equals(c));
}
}This prints CounterProxy, then 1 2, then true. The handler returns ++state[0], an int that autoboxes to Integer, which the proxy unboxes for the int return type. The equals result also autoboxes, which is the expected type for a boolean method.
Choosing and testing proxies
Use a dynamic proxy when one cross-cutting behavior must apply to many interface methods and you don't want to write a wrapper class per interface. Typical cases are logging, timing, retry, caching, access control, and test doubles.
Prefer a hand-written wrapper when the interface is small and the behavior is specific. A normal class is easier to read, debug, and refactor, and the compiler checks it.
Each call through a proxy adds a handler call plus a Method.invoke, which costs more than a direct call. The next chapters compare Method.invoke with method handles and discuss reflection costs more broadly. For most business code, the overhead is small compared with the I/O it surrounds.
You can check whether an object is a proxy with Proxy.isProxyClass(obj.getClass()), and you can get its handler with Proxy.getInvocationHandler(obj). These are mainly useful in tests and debugging tools.
Exercise
A handler for the interface interface Stats { int count(); } is written as (proxy, method, args) -> null. What happens when you call stats.count() on the proxy, and how do you fix it?
Show answer
The proxy tries to convert the returned null to the primitive int, so it throws a NullPointerException. The handler must return a non-null value that matches the return type, for example return 0;, which autoboxes to Integer and then unboxes to int. If the handler is shared by methods with different return types, check method.getReturnType() and return a matching default for each primitive.
Exercise
In TimingHandler, what would the caller of calc.divide(1, 0) see if the handler did not catch InvocationTargetException, and why?
Show answer
The handler's invoke method declares throws Throwable, so the InvocationTargetException would propagate out of it. The method divide does not declare that checked exception, so the proxy would wrap it in an UndeclaredThrowableException. The caller would see that instead of the ArithmeticException. Throwing e.getCause() passes the real exception through unchanged.