Lesson · Reflection, Proxies & Method Handles
Dynamic Proxies
11 min readDynamic Proxies
A dynamic proxy is a class the runtime writes for you: it implements the interfaces you name and funnels every call into one handler method. One class, many methods, one place to answer them.
One handler instead of a wrapper per method
You want a log line, a timer, a cache or a retry around an interface, without touching the implementation and without writing a decorator per method. The interface has ten methods today and will have twelve next sprint, so a hand-written wrapper means writing, and keeping correct, all of them.
A dynamic proxy replaces that wrapper with one class generated at run time. You supply a class loader, the list of interfaces, and one handler; the runtime supplies a class that implements every method of those interfaces and routes each call into your handler. The caller keeps seeing the interface it always saw.
// the client code below does not change, and it never learns a proxy is in front of it OrderService orders = (OrderService) Proxy.newProxyInstance( OrderService.class.getClassLoader(), new Class<?>[] { OrderService.class }, new AuditHandler(realOrders)); String receipt = orders.charge(42L);
One handler replaces a wrapper class per interface. The proxy is not generated per method; it is generated so that all methods arrive at a single entry point.
What newProxyInstance actually gives you
Proxy.newProxyInstance(loader, interfaces, handler) does three things: it resolves or defines a proxy class for that interface list and that loader, it creates an instance of it, and it stores the handler in it. Only interfaces are accepted, never classes or primitives, and every interface must be visible by name through the loader you pass.
The generated class is ordinary bytecode with documented properties, and those properties are what you are allowed to rely on.
| Property | What follows from it |
|---|---|
| final and non-abstract, extends java.lang.reflect.Proxy | you cannot subclass it, instanceof Proxy is true, and Proxy.getInvocationHandler(proxy) hands the handler back |
| implements exactly the interfaces, in the order given | the order is part of the identity: the same interfaces in a different order produce a different class |
| one class per loader plus interface permutation, cached | two calls with the same list return instances of the same class, so pass a stable array and the class is defined once |
| the package and module come from the interfaces | all-public interfaces give a public class in an unspecified exported package; a non-public interface makes the proxy non-public and places it beside that interface |
The class is cached; the instance is not. Defining a proxy class is the expensive part, and it happens once per loader and interface list; the handler is per instance.
Every call lands in one invoke
Every interface method arrives at invoke(Object proxy, Method method, Object[] args). The Method object identifies the call, the arguments come in as an Object array with primitives boxed, and whatever the handler returns becomes the caller's result.
Two categories of method arrive that surprise people. The first is Object's trio: hashCode, equals and toString are proxied too, with java.lang.Object as the declaring class of the Method, because a caller may always invoke them. The second is default methods: a proxy does not quietly run the interface's default implementation, it routes the call to your handler, and since JDK 16 you can delegate back to it with InvocationHandler.invokeDefault(proxy, method, args).
The first category is where the classic failure lives. A handler that logs by calling proxy.toString(), directly or through string concatenation, re-enters invoke, because toString is proxied like everything else. If the handler does not answer Object methods before its forwarding logic, nothing terminates that recursion except the stack.
- Method identity comes from the interface: the declaring class of the Method is the interface that declared it, which may be a superinterface of the one you proxied.
- Duplicates across interfaces: when two proxy interfaces declare the same signature, the Method you receive belongs to the first interface in the list that declares it.
- Return values are translated: a primitive must come back boxed, and returning null for a primitive return type makes the proxy throw NullPointerException to the caller.
- Answer Object methods first: one name check at the top of invoke prevents both the recursion and accidental equality by delegation.
One class for many methods, so every method has to be answered in one place. The handler sees everything, the three methods every object has included.
Dynamic proxies · one call, four stations
An interface and a real implementation already exist. The client would call orders.charge(42L) directly, and nothing at that call site will change if the object in front of it turns out to be a proxy.
Interfaces only, and the alternative when that is not enough
Dynamic proxies implement interfaces, and that is the whole of their reach. They cannot proxy a class, because the generated class already extends Proxy and Java has single inheritance. Intercepting a concrete type therefore needs bytecode generation or instrumentation, which is the territory of libraries such as Byte Buddy and CGLIB rather than the JDK.
- A class, enum or record cannot be a proxy interface: passing one to newProxyInstance throws IllegalArgumentException, as does a hidden or sealed interface.
- Non-public interfaces must share a package and a module, or the proxy class cannot be defined at all.
- No duplicate elements in the interface array, and every type mentioned in the interface signatures must be loadable by the loader you passed.
- Byte Buddy and CGLIB are the class-shaped answer, and they are also why the JDK proxy remains the first choice whenever a real interface exists.
If the shape is an interface, start with the JDK proxy; if it is a class, you are choosing a bytecode library. Naming that decision early tells you what your interception can ever see.
Where it earns its place
The pattern pays off wherever a concern belongs to a boundary rather than to one method. Logging, timing, retry, circuit breaking, caching and transaction or security decoration are each one invoke method away, which is why the AOP machinery in Spring and its relatives is built on this foundation; the sibling lesson Where Reflection Shows Up looks at the same mechanism from the framework's side.
Test doubles are the other big customer: a mock is a proxy whose handler answers from a script, returning 42 for one call and throwing for the next. Connection pools wrap the real Connection, Statement and ResultSet interfaces so that the close() a caller invokes returns the connection to the pool instead of closing it.
- Interception: one handler per concern, shared by every method of the interface.
- Wrappers that must not leak the real object: a pooled connection hands out a proxy, so close means return to the pool.
- Test doubles: mocks and spies are proxies with scripted handlers, which is why mocking libraries lean on the JDK proxy.
- The dark use: The Serialization Security Problem shows a proxy arriving inside serialized data as the dispatcher stage of a gadget chain. The mechanism is this lesson's; the payload is the handler.
The proxy is a seam, not a feature. Any behaviour that belongs to a boundary is a candidate for the handler, and the call site never changes.
Structure · one generated class, one entry point
one class per loader plus interface list, cached
Object methods arrive with java.lang.Object as the declaring class, which is why a handler that forwards everything can recurse on its own log line.
Exceptions and return values across the boundary
The handler's invoke declares throws Throwable, and the proxy translates what it throws into the call the client made. The rules are short, and the failure modes are indirect enough to be worth memorising.
| Handler does | Client sees |
|---|---|
| throws an unchecked exception | that exception, unchanged |
| throws a checked exception declared by the interface method | that exception, unchanged |
| throws a checked exception the method does not declare | UndeclaredThrowableException wrapping it, because the proxy cannot throw what the interface never promised |
| returns null for a primitive return type | NullPointerException from the invocation, thrown while unboxing |
| returns an incompatible type | ClassCastException at the call |
| returns the right type | the value, exactly as the target would have returned it |
The proxy can only throw what the interface promised, or an unchecked wrapper. Translate failures into the interface's own vocabulary inside the handler rather than letting UndeclaredThrowableException reach the caller.
Object methods are proxied too
equals, hashCode and toString are dispatched to your handler like any interface method, with java.lang.Object as the declaring class of the Method. A handler that forwards everything to the target therefore gives you the target's equality, which usually works and occasionally surprises; a handler that formats the proxy itself recurses until the stack ends. Answer the three by name in every handler: equals as proxy == args[0], hashCode as System.identityHashCode(proxy), toString as a fixed label or the target's string.
Interview angles
What does Proxy.newProxyInstance return, and what gets generated?+
An instance of a class generated for that class loader and that exact interface list: final, extending java.lang.reflect.Proxy, implementing the interfaces in order, with every method routed into the supplied InvocationHandler. The class is cached per loader and interface permutation, so later calls reuse it.
Because the class is shared and only the handler is per instance, two proxies of the same interface list in one loader are instances of the same class; compare them with the handler and the target in mind, not with instanceof.
How do you add behaviour around an interface without writing a decorator?+
Write one InvocationHandler: it receives the Method and the boxed arguments, does its before and after work, and forwards through method.invoke(target, args). One class covers every method of the interface, including the ones added next sprint.
Follow-up: What would you check before forwarding, and why?
Why does a proxy handler sometimes overflow the stack?+
Because the handler invoked a method on the proxy itself. toString, equals and hashCode are proxied, so that call re-enters invoke, which can call it again on the same path. Answer Object methods by name at the top of the handler and delegate only the interface methods.
Common misconception: That Object methods bypass the handler. They do not: the Method arrives with java.lang.Object as its declaring class and the call routes exactly like the rest.
What can a dynamic proxy not do?+
It cannot proxy a class, so intercepting a concrete type needs bytecode generation such as Byte Buddy or CGLIB. Non-public interfaces must share a package and module, and the interface list may not repeat an element or include a hidden or sealed interface.
Default methods are routed to the handler as well; since JDK 16 the handler can invoke the interface's own default implementation with InvocationHandler.invokeDefault(proxy, method, args) instead of reimplementing it.