Dynamic proxies
A dynamic proxy is an object the JVM creates at run time that implements one or more interfaces by sending every method call to a single handler. That one handler can add logging, retries, caching or security checks to every method without touching the real class. This page explains what the JVM generates, builds logging, retry and target-less proxies, runs the traps around equals, primitives and exceptions, shows why calls on this bypass a proxy, handles default methods, and measures the cost.
Contents
What Proxy.newProxyInstance creates
java.lang.reflect.ProxyInvocationHandler$Proxy0Proxyinvoke(proxy, method, args)MethodObject[]invoke
Three consequences shape every proxy you write:
- Only interfaces can be proxied. The generated class already extends
, so it cannot extend your class. Libraries such as Byte Buddy, used by Spring and Mockito, generate subclasses to proxy classes.Proxy - The handler receives every call, including
,equals andhashCode fromtoString .Object - Calls the real object makes on itself never pass through the proxy, because inside the target,
is the target.this
The generated class is final and overrides equalshashCodetoStringjava.util.function.Supplierjdk.proxy1.$Proxy0$Proxy1-Djdk.proxy.ProxyGenerator.saveGeneratedFiles=true.classjavap -c
newProxyInstanceIllegalArgumentException: java.lang.String is not an interfaceString name()ABMethodBmethod.getDeclaringClass()
| Technique | Since | Works on | Best for |
|---|---|---|---|
| Hand-written decorator | Any version | Interfaces or classes | One or two interfaces, maximum speed and clarity |
ProxyInvocationHandler | Java 1.3 | Interfaces only | One cross-cutting concern for many interfaces |
InvocationHandler.invokeDefault | Java 16 | Default methods of proxied interfaces | Proxies of interfaces that contain logic |
MethodHandleProxies.asInterfaceInstance | Java 7 | Single-method interfaces | Turning a method handle into an interface object |
| Bytecode libraries (Byte Buddy, cglib) | External | Classes and interfaces | Frameworks that must proxy concrete classes |
These proxy examples ran on JDK 21.
A logging proxy
A calculator with one method that succeeds and one that throws gets a handler that logs every call, its arguments and its result, without any change to the calculator class.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class LoggingProxy {
interface Calculator {
int add(int a, int b);
int divide(int a, int b);
}
static class RealCalculator implements Calculator {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int divide(int a, int b) {
return a / b;
}
}
// One handler intercepts EVERY method of the interface
static class Logger implements InvocationHandler {
private final Object target;
Logger(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(" -> " + method.getName() + Arrays.toString(args));
try {
Object result = method.invoke(target, args); // call the real object
System.out.println(" <- " + result);
return result;
} catch (InvocationTargetException e) {
System.out.println(" !! " + e.getCause());
throw e.getCause(); // rethrow the real exception
}
}
}
@SuppressWarnings("unchecked")
static <T> T logged(T target, Class<T> type) {
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},
new Logger(target));
}
public static void main(String[] args) {
Calculator calc = logged(new RealCalculator(), Calculator.class);
System.out.println("add: " + calc.add(2, 3));
try {
calc.divide(1, 0);
} catch (ArithmeticException e) {
System.out.println("caller caught: " + e.getMessage());
}
System.out.println("generated class name starts with $Proxy: "
+ calc.getClass().getSimpleName().startsWith("$Proxy"));
System.out.println("Proxy.isProxyClass: " + Proxy.isProxyClass(calc.getClass()));
}
}
Output:
-> add[2, 3]
<- 5
add: 5
-> divide[1, 0]
!! java.lang.ArithmeticException: / by zero
caller caught: / by zero
generated class name starts with $Proxy: true
Proxy.isProxyClass: true
- One handler logged both methods; adding a method to the interface would be logged too, without touching the handler. The arguments arrive boxed in an array, printed as
.[2, 3] wraps any exception thrown by the target inmethod.invoke(target, args) . The handler unwraps it withInvocationTargetException and rethrows the original, so the caller caught a plaingetCause() exactly as without the proxy.ArithmeticException- The object's class is a generated
class, and$Proxy recognizes it. The interfaces must be visible from the given class loader, which is whyProxy.isProxyClass is passed.type.getClassLoader()
A retry proxy and a proxy without a target
A price service that fails twice before succeeding, like a flaky network call, gets a handler that retries. The second proxy has no target at all: the handler is the whole implementation, which is how configuration and repository interfaces are often implemented by frameworks.
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RetryProxy {
interface PriceService {
double price(String sku);
}
// Fails twice, then works: like a flaky network call
static class FlakyService implements PriceService {
private int calls;
@Override
public double price(String sku) {
calls++;
if (calls < 3) {
throw new IllegalStateException("timeout on attempt " + calls);
}
return 19.99;
}
}
static <T> T withRetry(T target, Class<T> type, int attempts) {
InvocationHandler h = (proxy, method, args) -> {
for (int i = 1; ; i++) {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
System.out.println(" attempt " + i + " failed: " + e.getCause().getMessage());
if (i == attempts) {
throw e.getCause();
}
}
}
};
Object proxy = Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, h);
return type.cast(proxy);
}
// A proxy with NO target: the handler is the whole implementation
@SuppressWarnings("unchecked")
static <T> T inMemoryConfig(Class<T> type, Map<String, Object> values) {
Map<String, Object> store = new ConcurrentHashMap<>(values);
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type},
(proxy, method, args) -> store.get(method.getName()));
}
interface AppConfig {
String host();
Integer port();
}
public static void main(String[] args) {
PriceService service = withRetry(new FlakyService(), PriceService.class, 5);
System.out.println("price: " + service.price("A-1"));
AppConfig cfg = inMemoryConfig(AppConfig.class, Map.of("host", "localhost", "port", 8080));
System.out.println("config: " + cfg.host() + ":" + cfg.port());
}
}
Output:
attempt 1 failed: timeout on attempt 1
attempt 2 failed: timeout on attempt 2
price: 19.99
config: localhost:8080
- The handler retried after attempts 1 and 2 and returned the third attempt's 19.99. The caller saw only the successful result; with 5 attempts allowed, a sixth failure would have been rethrown unwrapped.
- Retrying is only safe for idempotent methods. A real retry proxy reads an annotation on
, such asmethod , to decide which calls may be repeated.@Retry(times = 3) - The configuration proxy answered
andhost() by looking the method name up in a map. No class implementsport() ; Spring Data repositories and many configuration libraries work on the same principle.AppConfig
Proxy traps: equals, primitives and exceptions
Each handler below is one line shorter than it should be, and each mistake shows up only at run time.
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public class ProxyTraps {
interface Repo {
int count();
String find(int id);
}
static class RealRepo implements Repo {
public int count() {
return 3;
}
public String find(int id) {
return "item-" + id;
}
@Override
public String toString() {
return "RealRepo";
}
}
static Repo proxy(InvocationHandler h) {
return (Repo) Proxy.newProxyInstance(Repo.class.getClassLoader(),
new Class<?>[] {Repo.class}, h);
}
public static void main(String[] args) {
Repo target = new RealRepo();
// 1. equals, hashCode and toString also go to the handler
Repo forwarding = proxy((p, m, a) -> {
try {
return m.invoke(target, a);
} catch (InvocationTargetException e) {
throw e.getCause();
}
});
System.out.println("1. toString: " + forwarding + ", proxy.equals(itself): "
+ forwarding.equals(forwarding) + ", hash same as target: "
+ (forwarding.hashCode() == target.hashCode()));
// 2. Returning null for a primitive return type
Repo lazy = proxy((p, m, a) -> m.getName().equals("find") ? "stub" : null);
try {
lazy.count();
} catch (NullPointerException e) {
System.out.println("2. null returned for int count(): NullPointerException");
}
// 3. Throwing a checked exception the interface does not declare
Repo failing = proxy((p, m, a) -> {
throw new IOException("disk gone");
});
try {
failing.find(1);
} catch (UndeclaredThrowableException e) {
System.out.println("3. undeclared IOException arrives as "
+ e.getClass().getSimpleName() + ", cause: " + e.getCause().getMessage());
}
// 4. Forgetting to unwrap InvocationTargetException
Repo unwrapped = proxy((p, m, a) -> m.invoke(new Repo() {
public int count() {
throw new IllegalStateException("db down");
}
public String find(int id) {
return null;
}
}, a));
try {
unwrapped.count();
} catch (UndeclaredThrowableException e) {
System.out.println("4. caller sees " + e.getClass().getSimpleName() + " -> "
+ e.getCause().getClass().getSimpleName() + " -> "
+ e.getCause().getCause().getMessage());
}
}
}
Output:
1. toString: RealRepo, proxy.equals(itself): false, hash same as target: true
2. null returned for int count(): NullPointerException
3. undeclared IOException arrives as UndeclaredThrowableException, cause: disk gone
4. caller sees UndeclaredThrowableException -> InvocationTargetException -> db down
- The forwarding handler also forwarded
andtoString , so the proxy printed as "RealRepo" and had the target's hash code. ButhashCode was false: the call becameproxy.equals(proxy) , and the target is not equal to the proxy. Proxies put into atarget.equals(proxy) or used as map keys then misbehave. Handle the threeHashSet methods explicitly, as the default-method example below does.Object - Returning
fromnull for a method with a primitive return type, hereinvoke , throwsint count() when the proxy unboxes it.NullPointerException - A checked exception that the interface method does not declare, such as
, cannot reach the caller as itself. The proxy wraps it inIOException . Unchecked exceptions and declared checked exceptions pass through unchanged.UndeclaredThrowableException - Forgetting to unwrap
produced a double wrapping: the caller gotInvocationTargetException , whose cause is theUndeclaredThrowableException , whose cause is the real "db down". Error handling written for the real exception type never sees it.InvocationTargetException
Self-invocation bypasses the proxy
An order service's placeOrderaudit
import java.lang.reflect.Proxy;
public class SelfInvocation {
interface OrderService {
void placeOrder(String item);
void audit(String what);
}
static class RealOrderService implements OrderService {
public void placeOrder(String item) {
System.out.println(" placing " + item);
audit("order " + item); // a call on 'this', not on the proxy
}
public void audit(String what) {
System.out.println(" audit: " + what);
}
}
public static void main(String[] args) {
RealOrderService real = new RealOrderService();
OrderService proxy = (OrderService) Proxy.newProxyInstance(
OrderService.class.getClassLoader(), new Class<?>[] {OrderService.class},
(p, m, a) -> {
System.out.println(" [proxy] before " + m.getName());
return m.invoke(real, a);
});
System.out.println("calling placeOrder through the proxy:");
proxy.placeOrder("book");
System.out.println("calling audit through the proxy:");
proxy.audit("manual check");
}
}
Output:
calling placeOrder through the proxy:
[proxy] before placeOrder
placing book
audit: order book
calling audit through the proxy:
[proxy] before audit
audit: manual check
- When
was called through the proxy, the handler saw it, but theplaceOrder call made insideaudit did not appear: it was a plain call onplaceOrder , the real object. Only the directthis call passed through the handler.proxy.audit - This is the reason a Spring
or@Transactional method called from another method of the same bean has no effect: the annotation is implemented by a proxy, and the internal call never reaches it. The usual fixes are to move the method to another bean, or to call it through a reference to the proxy.@Cacheable
Default methods and Object methods
Since Java 8, an interface can contain default methods with real logic. A proxy's handler receives them like any other method, and before Java 16 there was no clean way to run the interface's own implementation. A configuration interface with a url()equalshashCodetoString
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.TreeMap;
public class DefaultMethods {
// A configuration interface: abstract getters plus a default method with logic
interface ServerConfig {
String host();
Integer port();
default String url() {
return "https://" + host() + ":" + port();
}
}
public static void main(String[] args) {
Map<String, Object> values = new TreeMap<>(Map.of("host", "api.example.com", "port", 8443));
InvocationHandler h = (proxy, method, a) -> {
if (method.isDefault()) {
// Java 16: run the interface's own default implementation on this proxy
return InvocationHandler.invokeDefault(proxy, method, a);
}
if (method.getDeclaringClass() == Object.class) {
return switch (method.getName()) {
case "toString" -> "ServerConfig" + values;
case "hashCode" -> System.identityHashCode(proxy);
case "equals" -> proxy == a[0];
default -> throw new UnsupportedOperationException(method.getName());
};
}
return values.get(method.getName());
};
ServerConfig cfg = (ServerConfig) Proxy.newProxyInstance(
ServerConfig.class.getClassLoader(), new Class<?>[] {ServerConfig.class}, h);
System.out.println("host(): " + cfg.host());
System.out.println("url(): " + cfg.url() + " (a default method)");
System.out.println("toString: " + cfg);
System.out.println("equals itself: " + cfg.equals(cfg));
}
}
Output:
host(): api.example.com
url(): https://api.example.com:8443 (a default method)
toString: ServerConfig{host=api.example.com, port=8443}
equals itself: true
ran the interface'sInvocationHandler.invokeDefault(proxy, method, args) body on the proxy. Inside it,url() andhost() were calls on the proxy and came back through the handler, giving "https://api.example.com:8443".port()- The handler answers the three
methods itself: a readableObject , identity-basedtoString , andhashCode that compares the proxy with the argument. Now the proxy equals itself and behaves correctly in hash-based collections.equals - The values map is a
so thatTreeMap lists keys in the same order on every run;toString iteration order changes between JVM runs.Map.of
What a proxy call costs
A trivial operation, doubling an int, is called 10 million times directly, through a hand-written wrapper, and through a dynamic proxy whose handler forwards with Method.invoke
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.util.Random;
import java.util.function.IntUnaryOperator;
public class ProxyCost {
static final class Doubler implements IntUnaryOperator {
@Override
public int applyAsInt(int x) {
return x * 2;
}
}
static final int[] DATA = new Random(1).ints(1024, 0, 100).toArray();
static double ns(IntUnaryOperator op, int n) {
long best = Long.MAX_VALUE;
long sink = 0;
for (int r = 0; r < 5; r++) {
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
sink += op.applyAsInt(DATA[i & 1023]);
}
best = Math.min(best, System.nanoTime() - t0);
}
if (sink == 42) {
System.out.println();
}
return (double) best / n;
}
public static void main(String[] args) {
IntUnaryOperator direct = new Doubler();
IntUnaryOperator decorator = x -> direct.applyAsInt(x); // hand-written wrapper
IntUnaryOperator proxy = (IntUnaryOperator) Proxy.newProxyInstance(
ProxyCost.class.getClassLoader(), new Class<?>[] {IntUnaryOperator.class},
(p, m, a) -> {
try {
return m.invoke(direct, a);
} catch (InvocationTargetException e) {
throw e.getCause();
}
});
int n = 10000000;
System.out.printf("%,d calls, best of 5 runs%n", n);
System.out.printf("direct object: %6.2f ns per call%n", ns(direct, n));
System.out.printf("hand-written decorator: %6.2f ns per call%n", ns(decorator, n));
System.out.printf("dynamic proxy: %6.2f ns per call%n", ns(proxy, n));
}
}
Output (2-CPU Linux machine, JDK 21, best of 5):
10,000,000 calls, best of 5 runs
direct object: 0.33 ns per call
hand-written decorator: 0.87 ns per call
dynamic proxy: 3.49 ns per call
- The proxy was several times slower than the hand-written wrapper here, but still only a few nanoseconds per call: it boxes the argument into an array, calls the handler, calls
, and unboxes the result.Method.invoke - For a proxy around a database call or an HTTP client, a few nanoseconds are nothing. For a proxy around a method called millions of times in a tight loop, write a decorator instead.
- The handler should avoid repeated reflection lookups, such as reading annotations from
on every call. Cache what it needs permethod in a map, as frameworks do.Method
Choosing a proxy technique
| Situation | Use |
|---|---|
| The same concern (logging, timing, retries) on many interfaces | A dynamic proxy with one handler |
| Implementing an interface from metadata alone | A target-less proxy |
| A single interface, performance-sensitive | A hand-written decorator |
| Interfaces with default methods | InvocationHandler.invokeDefault |
| Proxying a concrete class | A bytecode library, or extract an interface |
| Behaviour that must also apply to internal calls | Put the logic in the class itself, or call through the proxy reference |
Handlers rely on