Java Dynamic Proxies: Implementing Interfaces at Runtime
Learn Java dynamic proxies: when you need classes created at runtime, InvocationHandler and Proxy.newProxyInstance, tracing calls with a proxy, which Object methods are forwarded, invokeDefault for default methods (Java 16), proxy class properties, and real-world uses in frameworks.
kvi5hnuCode Sprout team member11 min readOn this page
The final topic of this part is proxies. A proxy lets you create, at runtime, new classes that implement a given set of interfaces. Proxies are only necessary when you don't yet know at compile time which interfaces you need to implement. That's rare for application programmers, so feel free to skip this article if you're not interested in advanced wizardry. But for certain systems programming tasks, the flexibility of proxies is very important, and you use them all the time without noticing: Spring's @Transactional, JPA repositories, mocking libraries and RPC clients are often built on them.
When to Use Proxies
Suppose you want to construct an object of a class that implements one or more interfaces whose exact nature you may not know at compile time. That's a hard problem. To construct an object of an actual class, you can use newInstance or find a constructor with reflection. But you can't instantiate an interface. You need to define a new class in a running program.
Some programs solve this by generating code, writing it to a file, invoking the compiler, and loading the resulting class file. Naturally, that's slow, and it requires deploying the compiler with the program. The proxy mechanism is a better solution. It creates brand-new classes at runtime that implement the interfaces you specify. A proxy class has:
- all methods required by the specified interfaces, and
- all methods defined in the
Objectclass (toString,equals, and so on).
However, you can't supply new code for these methods at runtime. Instead, you supply an invocation handler: an object of any class that implements the InvocationHandler interface, which has a single method:
Object invoke(Object proxy, Method method, Object[] args)
Whenever a method is called on the proxy object, the handler's invoke method is called with the Method object and the arguments of the original call. The handler must then figure out how to handle the call.

Creating Proxy Objects
To create a proxy object, call the static newProxyInstance method of the java.lang.reflect.Proxy class. It has three parameters:
- A class loader. Different class loaders can be used for platform classes, application classes, plugins, and so on. Here we use the "system class loader" that loads platform and application classes. A common choice in libraries is the class loader of the interface itself,
MyInterface.class.getClassLoader(). - An array of
Classobjects, one for each interface to be implemented. - An invocation handler.
Two questions remain: how do we define the handler, and what can we do with the proxy object? The answers depend on the problem you're solving. Proxies are used for purposes such as:
- routing method calls to remote servers,
- associating user interface events with actions in a running program,
- tracing method calls for debugging,
- adding cross-cutting behavior such as transactions, caching, security checks or timing,
- creating test doubles (mocks) for interfaces.
A tracing proxy
Let's use proxies and invocation handlers to trace method calls. We define a TraceHandler wrapper class that stores a wrapped object. Its invoke method prints the name and arguments of the called method, then calls the method with the wrapped object as the implicit argument:
class TraceHandler implements InvocationHandler {
private Object target;
public TraceHandler(Object t) {
target = t;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
// print method name and arguments
. . .
// invoke actual method
return m.invoke(target, args);
}
}
Here's how to construct a proxy object that traces whenever one of its methods is called:
Object value = . . .;
// construct wrapper
var handler = new TraceHandler(value);
// construct proxy for one or more interfaces
Object proxy = Proxy.newProxyInstance(
ClassLoader.getSystemClassLoader(),
new Class<?>[] { Comparable.class }, handler);
Now, whenever a method of one of the interfaces is called on proxy, the method name and arguments are printed, and the method is then invoked on value.
Tracing a binary search
The following program uses proxy objects to trace a binary search. It fills an array with proxies for the integers 1 to 1000, then calls Arrays.binarySearch to search for a key, and finally prints the matching element. (We use the fixed key 288 so the output is reproducible; try a random key yourself.)
Integer implements Comparable. The proxy objects belong to a class defined at runtime, with a name such as $Proxy0, which also implements Comparable. Its compareTo method calls invoke of the proxy's handler.
binarySearch makes calls like
if (elements[i].compareTo(key) < 0) . . .
Since the array is full of proxies, compareTo calls TraceHandler.invoke, which prints the method name and arguments and then invokes compareTo on the wrapped Integer. At the end, the program calls System.out.println(elements[result]). println calls toString on the proxy, and that call is also routed to the invocation handler.
import java.lang.reflect.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
var elements = new Object[1000];
// fill elements with proxies for the integers 1 . . . 1000
for (int i = 0; i < elements.length; i++) {
Integer value = i + 1;
var handler = new TraceHandler(value);
Object proxy = Proxy.newProxyInstance(
ClassLoader.getSystemClassLoader(),
new Class<?>[] { Comparable.class }, handler);
elements[i] = proxy;
}
// a fixed key, so the trace is reproducible (use new Random().nextInt(...) for variety)
Integer key = 288;
// search for the key
int result = Arrays.binarySearch(elements, key);
// print match if found
if (result >= 0) System.out.println(elements[result]);
// properties of proxy classes
Class<?> cl = elements[0].getClass();
System.out.println(Proxy.isProxyClass(cl) + " " + cl.getSimpleName().startsWith("$Proxy")
+ " " + Modifier.toString(cl.getModifiers()) + " " + (cl.getSuperclass() == Proxy.class));
System.out.println(elements[0].getClass() == elements[1].getClass()); // one class, many objects
// a proxy for our own interface: timing/logging around a real object, default methods passed through
Greeter real = name -> "Hello, " + name;
Greeter logged = (Greeter) Proxy.newProxyInstance(
Greeter.class.getClassLoader(), new Class<?>[] { Greeter.class },
(proxy, method, methodArgs) -> {
if (method.isDefault())
return InvocationHandler.invokeDefault(proxy, method, methodArgs);
System.out.println("-> " + method.getName() + Arrays.toString(methodArgs));
Object r = method.invoke(real, methodArgs);
System.out.println("<- " + r);
return r;
});
System.out.println(logged.greetAll(List.of("Ada", "Linus")));
}
}
/**
* An invocation handler that prints out the method name and parameters, then
* invokes the original method.
*/
class TraceHandler implements InvocationHandler {
private final Object target;
/**
* Constructs a TraceHandler.
* @param t the implicit parameter of the method call
*/
public TraceHandler(Object t) {
target = t;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
// print implicit argument
System.out.print(target);
// print method name
System.out.print("." + m.getName() + "(");
// print explicit arguments
if (args != null) {
for (int i = 0; i < args.length; i++) {
System.out.print(args[i]);
if (i < args.length - 1) System.out.print(", ");
}
}
System.out.println(")");
// invoke actual method
return m.invoke(target, args);
}
}
interface Greeter {
String greet(String name);
default String greetAll(List<String> names) {
var sj = new StringJoiner("; ");
for (String n : names) sj.add(greet(n)); // calls go through the proxy again
return sj.toString();
}
}
500.compareTo(288)
250.compareTo(288)
375.compareTo(288)
312.compareTo(288)
281.compareTo(288)
296.compareTo(288)
288.compareTo(288)
288.toString()
288
true true public final true
true
-> greet[Ada]
<- Hello, Ada
-> greet[Linus]
<- Hello, Linus
Hello, Ada; Hello, Linus
The trace shows how binary search homes in on the key by halving the search interval at every step: 500, 250, 375, 312, 281, 296, 288. Note that toString is proxied even though it doesn't belong to Comparable. As you'll see next, certain Object methods are always proxied.
The second part of the program wraps an object implementing our own Greeter interface in a logging proxy. The handler is a lambda, because InvocationHandler is a functional interface.
Properties of Proxy Classes
Proxy classes are created on the fly in a running program. Once created, they're regular classes, like any other class in the virtual machine.
- All proxy classes extend the class
Proxy. A proxy class has only one instance field: the invocation handler, defined in theProxysuperclass. Any additional data needed to carry out the proxy's tasks must be stored in the invocation handler. That's whyTraceHandlerholds the wrapped object. - All proxy classes override
toString,equalsandhashCodeofObject. Like all proxy methods, they simply callinvokeon the handler. The other methods ofObject(such ascloneandgetClass) aren't redefined. - The names of proxy classes aren't specified. The JDK generates names that begin with
$Proxy; in recent versions they live in dynamically created packages or modules such asjdk.proxy1. - There's only one proxy class for a particular class loader and ordered set of interfaces. If you call
newProxyInstancetwice with the same class loader and interface array, you get two objects of the same class. The deprecated methodProxy.getProxyClass(loader, interfaces)returns that class; since Java 9, callnewProxyInstanceandgetClass()instead. - A proxy class is always
final. If all the interfaces it implements arepublic(and exported, with modules), the proxy class ispublicand lives in an unspecified, dynamically generated package and module (such asjdk.proxy1). Otherwise, all non-public interfaces must be in the same package, and the proxy class belongs to that package too. - You can test whether a
Classobject represents a proxy class withProxy.isProxyClass.
Default methods
Calling a default method on a proxy also goes to the invocation handler. To actually run the default method's code, the handler calls the static InvocationHandler.invokeDefault method (Java 16). Here's a handler that runs default methods and passes abstract methods to another target:
InvocationHandler handler = (proxy, method, args) -> {
if (method.isDefault())
return InvocationHandler.invokeDefault(proxy, method, args);
else
return method.invoke(target, args);
};
In the demo, greetAll is a default method. It runs through invokeDefault, and its internal calls to greet go through the proxy again, which is why each greeting is logged.
Exceptions and other pitfalls
- If the target method throws,
Method.invokewraps the exception in anInvocationTargetException. A well-behaved handler unwraps it (throw e.getCause()), so callers see the original exception. A checked exception that the interface method doesn't declare would reach the caller as anUndeclaredThrowableException. argsisnullfor methods without parameters, asTraceHandlertakes into account.- The handler's return value must match the method's return type. Returning
nullfor a primitive return type causes aNullPointerException. - Be careful with
equals. WhenTraceHandlerforwards it,proxy.equals(proxy)becomestarget.equals(proxy), and theIntegerdoesn't recognize the proxy, so a proxy isn't even equal to itself. Handlers that care about equality should implementequalsandhashCodethemselves, for example by comparing proxy identity.
Proxies in the Real World
The JDK's proxies only work for interfaces. Frameworks that need to proxy classes generate subclasses at runtime with bytecode libraries such as Byte Buddy (used by Mockito and Hibernate), or the JDK's own Class-File API (java.lang.classfile, final in Java 24). The idea is the same: intercept method calls and route them through a handler.
| Use | Example |
|---|---|
| Declarative transactions, security, caching | Spring AOP proxies around @Transactional and @Cacheable beans |
| Repository interfaces with no implementation | Spring Data JPA turns interface UserRepository extends JpaRepository<User, Long> into a proxy |
| HTTP or RPC clients from interfaces | Feign, Retrofit, gRPC stubs |
| Mock objects in tests | Mockito's mock(MyInterface.class) |
| Annotations at runtime | Annotation instances returned by reflection are JDK proxies |
Wrapping Up Part 6
This ends the object-oriented features of the Java language. Interfaces, lambda expressions and inner classes are concepts you'll meet constantly. Cloning, service loaders and proxies are advanced techniques mainly of interest to library designers and tool builders, not application programmers. Next, you'll learn how to deal with exceptional situations: exceptions, assertions and logging.
Common questions
Can a JDK proxy implement a class instead of an interface?
No. java.lang.reflect.Proxy works only with interfaces. To intercept methods of a class, frameworks generate a subclass at runtime with a bytecode library such as Byte Buddy, or with the JDK's Class-File API (final in Java 24). That only works for non-final classes and methods.
Why is my proxy not equal to itself?
equals, hashCode and toString are routed to the invocation handler like every other method. If the handler forwards equals(proxy) to the target object, the target doesn't recognise the proxy. Handle these three methods in the handler yourself, for example by comparing identity with proxy == args[0].
How does Spring's @Transactional relate to proxies?
Spring wraps your bean in a proxy, a JDK proxy for interfaces or a generated subclass otherwise. The proxy starts a transaction, calls your method, and commits or rolls back. That's also why a @Transactional method called from inside the same object (this.save()) bypasses the proxy and runs without a transaction.
Are dynamic proxies slow?
Each call goes through invoke with a Method object and an Object[] of arguments, so it is slower than a direct call. Proxies are fine for cross-cutting concerns around coarse-grained calls such as service methods, remote calls and repositories, but not for tight inner loops.
How do I call a default method from an invocation handler?
Use InvocationHandler.invokeDefault(proxy, method, args) (Java 16). Calling method.invoke(proxy, args) would route the call straight back into the handler and recurse forever.
Summary
- A dynamic proxy is an instance of a class generated at runtime that implements a list of interfaces. Create one with
Proxy.newProxyInstance(classLoader, interfaces, handler). - Every interface method call, plus
toString,equalsandhashCode, is routed toInvocationHandler.invoke(proxy, method, args), which typically delegates to a target withmethod.invoke(target, args). - Proxy classes extend
Proxy, are final, have the handler as their only state, are shared per class loader and interface list, and can be detected withProxy.isProxyClass. - Use
InvocationHandler.invokeDefaultto run default methods (Java 16). UnwrapInvocationTargetExceptionin handlers. - Proxies power tracing, remote calls, transactions, repositories and mocks. For classes rather than interfaces, frameworks generate subclasses with bytecode tools.
Practice Questions
Why can't you just use reflection's newInstance to create an object implementing an interface you discover at runtime?
newInstance needs an existing class, and an interface can't be instantiated. A proxy creates a new class at runtime that implements the interface, with all calls routed to your handler.
In TraceHandler, why does println(elements[result]) print a trace line too, even though toString isn't in Comparable?
Proxy classes always override toString, equals and hashCode of Object and route them through the invocation handler.
Where does a proxy keep the object it wraps?
In the invocation handler. The proxy class's only instance field is the handler, inherited from Proxy, so any extra state must live in the handler.
Write an invocation handler that measures how long each call on a target takes and rethrows the original exception if the target throws.
InvocationHandler timing = (proxy, method, args) -> {
long start = System.nanoTime();
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause();
} finally {
System.out.println(method.getName() + " took " + (System.nanoTime() - start) + " ns");
}
};
You create two proxies with the same class loader and the interfaces {Runnable.class, Comparable.class}. Do they have the same class? What about {Comparable.class, Runnable.class}?
The first two share one proxy class. Reversing the interface order gives a different ordered list, and therefore a different proxy class.
Previous: Java ServiceLoader: Loading Pluggable Service Implementations
Next: Java Exceptions: The Exception Hierarchy, Checked and Unchecked
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.