Sub topic 4
JDK dynamic proxies
This chapter assumes you know Java interfaces, basic reflection (Method, invoke), and Spring beans. It covers how the JDK builds a proxy at runtime, which is the mechanism Spring AOP uses for beans that implement interfaces.
What a JDK dynamic proxy is
A JDK dynamic proxy is a class generated at runtime that implements one or more interfaces you name. Every method call on the proxy is routed to a single InvocationHandler. The handler decides what to do: run extra code, call the real object, or both.
You create one with java.lang.reflect.Proxy.newProxyInstance. It takes three arguments:
- A class loader, which defines the generated class.
- An array of interfaces the proxy must implement.
- An
InvocationHandler, whoseinvokemethod receives the proxy, theMethodcalled, and its arguments.
A worked example
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
interface GreetingService {
String greet(String name);
}
class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
public class ProxyDemo {
public static void main(String[] args) {
GreetingService target = new GreetingServiceImpl();
GreetingService proxy = (GreetingService) Proxy.newProxyInstance(
GreetingService.class.getClassLoader(),
new Class<?>[] { GreetingService.class },
(p, method, methodArgs) -> {
System.out.println("before " + method.getName());
try {
return method.invoke(target, methodArgs);
} catch (InvocationTargetException e) {
throw e.getCause();
}
});
System.out.println(proxy.greet("Ada"));
}
}Running it prints before greet, then Hello, Ada. The handler runs first and then delegates to target with method.invoke.
Common errors
- Casting to the class. The proxy implements
GreetingService, but it is not aGreetingServiceImpl. Casting to the implementation class throwsClassCastException. Code that depends on the concrete class cannot receive a JDK proxy. - Leaking
InvocationTargetException.method.invokewraps any exception thrown by the target. If the handler rethrows the wrapper, callers seeUndeclaredThrowableExceptionor the wrong type. Unwrap withe.getCause(), as the example does. - Calling a method on
p. Callingmethod.invoke(p, ...)inside the handler re-enters the handler and recurses forever. Always invoke on the target. - Expecting class-only methods. Only methods declared by the listed interfaces are intercepted. Public methods that exist only on the implementation class are not reachable through the proxy.
Limits to remember
The proxy forwards equals, hashCode and toString to the handler as well. Your handler therefore sees those calls, and a handler that assumes every call is a business method can misbehave on them.
Each proxy call also pays for reflection. For most applications this cost is small next to the work the advice does.
Exercise
In the example, a colleague changes the handler to call method.invoke(p, methodArgs) instead of method.invoke(target, methodArgs). What happens when proxy.greet("Ada") runs, and why?
Show answer
The call goes to the proxy itself, which routes it back to the same handler. The handler calls the proxy again, so the calls repeat until the stack overflows and a StackOverflowError is thrown. The handler must invoke the method on the real target object.
Exercise
A bean class OrderServiceImpl implements the interface OrderService. Another class declares a field of type OrderServiceImpl and asks Spring to inject it. If Spring wraps the bean in a JDK proxy, what goes wrong?
Show answer
The proxy implements OrderService but is not an OrderServiceImpl, so it cannot be assigned to the field and injection fails. Inject by the interface type OrderService instead.