Sub topic 4
JDK Dynamic Proxies
This chapter assumes you know Java interfaces, lambdas, and basic reflection (Method, invoke). It covers how the JDK builds a proxy at runtime, what the invocation handler receives, and the errors that most often catch people out. Spring AOP uses this mechanism for beans that implement interfaces.
What a JDK dynamic proxy is
A JDK dynamic proxy is a class that the JVM generates at runtime. It implements one or more interfaces you name. Every call on the proxy goes to a single InvocationHandler, and the handler decides what happens next.
You never write the proxy class. You call java.lang.reflect.Proxy.newProxyInstance with three arguments:
- A class loader that can see the interfaces.
- An array of the interfaces the proxy should implement.
- An
InvocationHandlerthat receives every call.
The returned object is an instance of a generated class, not of your implementation class. It can be cast to any interface you listed, and to nothing else.
A first proxy
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
Hello, AdaThe target is the real object. The proxy holds no business logic. It prints a line, then forwards the call with method.invoke(target, methodArgs). This is the same shape Spring AOP uses: advice runs around a delegated call to the target bean.
The three handler parameters
The handler has the signature Object invoke(Object proxy, Method method, Object[] args) throws Throwable.
| Parameter | Meaning | Common mistake |
|---|---|---|
| `proxy` | The generated proxy instance itself | Calling `method.invoke(proxy, args)`, which re-enters the handler and recurses until `StackOverflowError` |
| `method` | The interface method that was called | Expecting the implementation's method, so annotations on the implementation class are not visible |
| `args` | The arguments, or `null` for no-argument methods | Assuming it is never null |
The handler is declared throws Throwable, so it can rethrow anything the target throws.
Exceptions and `InvocationTargetException`
Method.invoke wraps any exception thrown by the target in an InvocationTargetException. The example unwraps it with e.getCause(). This matters because of how the proxy treats exceptions:
- If the handler throws an unchecked exception or an
Error, the caller sees it unchanged. - If the handler throws a checked exception that the interface method declares, the caller sees it unchanged.
- If the handler throws a checked exception that the interface method does not declare, the JVM wraps it in
UndeclaredThrowableException.
Without the unwrapping, a business exception such as IllegalArgumentException would reach the caller as an UndeclaredThrowableException wrapping an InvocationTargetException. Callers that catch the original type would then miss it. Spring's own proxies unwrap exceptions for this reason.
What the proxy intercepts
The generated class routes these calls to the handler:
- Every method of every listed interface.
- Three methods from
Object:hashCode(),equals(), andtoString().
Other Object methods, such as getClass(), are not routed. So a ProxyDemo check like proxy.getClass() reports the generated class, typically named like jdk.proxy1.$Proxy0 (or com.sun.proxy.$Proxy0 on older JDKs). Your handler must be ready for toString and hashCode calls. A handler that blindly forwards them to the target usually works, but one that assumes every call is a business method can fail on a debugger or logging statement that calls toString().
Type identity and casting
Because the proxy implements only interfaces, these rules follow:
proxy instanceof GreetingServiceistrue.proxy instanceof GreetingServiceImplisfalse.- Casting the proxy to
GreetingServiceImplthrowsClassCastException.
This is the most common source of trouble in Spring. If a bean implements an interface and you inject it by its concrete class, injection fails when a JDK proxy wraps the bean. Inject by the interface instead.
The diagram below shows the call path.
Limits of the mechanism
JDK proxies have limits that follow from how they are built.
- Interfaces only. If the class implements no interface,
Proxycannot proxy it. Spring then switches to CGLIB, which the next chapter covers. - Public interface methods only. Methods that are not part of an interface are not reachable through the proxy, even if they are public on the implementation class.
- Self-invocation bypasses the proxy. The target calls its own methods on
this, which is the real object. Those calls never reach the handler. A later chapter covers this in detail. - Reflection cost. Each call uses
Method.invoke. Modern JVMs optimize this well, so the overhead is rarely the reason to choose another approach. - Visibility of interfaces. A non-public interface must be loaded by the same class loader as the proxy class. Mixing loaders gives
IllegalArgumentExceptionat creation time.
How this connects to Spring
When Spring wraps a bean that implements interfaces, it does essentially what the example does. It builds an InvocationHandler (internally JdkDynamicAopProxy) that finds the advice that applies to the called method, runs it in order, and finally calls the target. Your aspect code replaces the System.out.println line.
Spring Boot defaults to CGLIB even for beans with interfaces (spring.aop.proxy-target-class=true). Plain Spring Framework uses a JDK proxy when the bean has at least one interface. The next chapter explains the difference and how Spring decides.
Checking your understanding
Exercise
A handler contains return method.invoke(proxy, args); and a caller calls proxy.greet("Ada"). What happens, and what should the handler call instead?
Show answer
The call goes back to the same handler, because proxy is the generated object. The handler calls itself over and over until a StackOverflowError. It should call method.invoke(target, args) on the real target object.
Exercise
A service class OrderServiceImpl implements OrderService is wrapped in a JDK proxy. Code does OrderServiceImpl s = (OrderServiceImpl) ctx.getBean("orderService"); and fails. Why, and how do you fix it?
Show answer
The proxy implements OrderService but is not a subclass of OrderServiceImpl, so the cast throws ClassCastException. Fix it by declaring the variable as OrderService. Alternatively, configure class-based (CGLIB) proxying, which creates a subclass of the implementation.
Exercise
The target method throws IllegalArgumentException. The handler calls method.invoke(target, args) with no try/catch and no unwrapping. What exception type does the caller receive, and why?
Show answer
The caller receives UndeclaredThrowableException. Method.invoke wraps the target's exception in InvocationTargetException, which is a checked exception that the interface method does not declare, so the proxy wraps it again. The handler should catch InvocationTargetException and throw e.getCause().