Sub topic 13
Dynamic proxies with InvocationHandler
This chapter assumes you can read Java interfaces and lambdas, and that you know how Method.invoke works from the earlier chapters on method invocation.
What a dynamic proxy is
A dynamic proxy is an object that the JDK builds at runtime. It implements one or more interfaces you name, and it forwards every method call to a single InvocationHandler. You do not write the proxy class. java.lang.reflect.Proxy generates it when you ask for it.
This is useful when you want to add behavior around calls without changing the target class. Typical uses are logging, timing, access checks, and transaction handling.
Creating a proxy
Proxy.newProxyInstance takes three arguments:
- A class loader, which defines the generated class. Use the interface's loader.
- An array of interfaces the proxy must implement.
- An
InvocationHandler, which receives every call.
InvocationHandler has one method, invoke(Object proxy, Method method, Object[] args). Because it has a single abstract method, you can write it as a lambda.
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"));
}
}The program prints calling greet and then Hello, Ada. The handler answers the call itself. No real Greeter implementation exists.
How a call flows
When you call g.greet("Ada"), the generated class does not run any greeting code. It packages the Method object and the arguments and passes them to your handler. Whatever the handler returns becomes the result of the call.
Wrapping a real object
Most handlers hold a target object and delegate to it, adding behavior before and after. Here the handler measures how long each call takes.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
interface Calculator {
int add(int a, int b);
}
class SimpleCalculator implements Calculator {
public int add(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, java.lang.reflect.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 {
public static void main(String[] args) {
Calculator real = new SimpleCalculator();
Calculator calc = (Calculator) Proxy.newProxyInstance(
Calculator.class.getClassLoader(),
new Class<?>[] { Calculator.class },
new TimingHandler(real));
System.out.println(calc.add(2, 3));
}
}Note the catch block. If the target throws, Method.invoke wraps the error in InvocationTargetException. The handler rethrows the cause so the caller sees the original exception.
Common errors
- Interfaces only. A proxy can implement interfaces but cannot extend a class. Passing a class type to
newProxyInstancethrowsIllegalArgumentException. Libraries such as CGLIB or Byte Buddy cover the subclass case. - Wrong cast. The proxy implements your interface but is not an instance of the target's class.
(SimpleCalculator) calcfails withClassCastException. - Null return for a primitive. If the interface method returns
intand the handler returnsnull, the call throwsNullPointerException. - Calling a method on
proxy. Insideinvoke, calling an interface method on theproxyargument re-enters the handler and recurses forever. Use your target instead. - Checked exceptions. If the handler throws a checked exception the interface method does not declare, the caller gets an
UndeclaredThrowableException. argscan be null. For methods with no parameters,argsisnull, not an empty array.
Exercise
A handler wraps a target and calls method.invoke(target, args). The target method throws IllegalStateException. What does the caller of the proxy see if the handler does not catch anything, and how do you make it see the original exception?
Show answer
The caller sees an UndeclaredThrowableException wrapping an InvocationTargetException, because the checked InvocationTargetException is not declared by the interface method. Catch InvocationTargetException in the handler and throw e.getCause() so the caller receives the IllegalStateException.
Exercise
Why does Proxy.newProxyInstance(loader, new Class<?>[] { ArrayList.class }, handler) fail?
Show answer
ArrayList is a class, not an interface. A dynamic proxy can only implement interfaces, so the call throws IllegalArgumentException.