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.Proxy (Java 1.3) generates a class at run time from three inputs: a class loader, a list of interfaces, and an InvocationHandler. The generated class, named like $Proxy0, extends Proxy and implements every listed interface. Each of its methods does the same thing: it calls the handler's invoke(proxy, method, args), passing the Method object of the interface method that was called and the arguments boxed into an Object[]. Whatever invoke returns is unboxed and cast to the method's return type.

Three consequences shape every proxy you write:

  • Only interfaces can be proxied. The generated class already extends Proxy, so it cannot extend your class. Libraries such as Byte Buddy, used by Spring and Mockito, generate subclasses to proxy classes.
  • The handler receives every call, including equals, hashCode and toString from Object.
  • Calls the real object makes on itself never pass through the proxy, because inside the target, this is the target.

The generated class is final and overrides equals, hashCode and toString along with the interface methods. Where it lives depends on the interfaces: a proxy for a public interface such as java.util.function.Supplier is placed in a dynamic module, with a name like jdk.proxy1.$Proxy0, while a proxy for a non-public interface must share that interface's package and appears as plain $Proxy1 in it. The class is created once per combination of loader and interfaces and then reused, so creating many proxies of the same kind is cheap. To look at the bytecode, run with -Djdk.proxy.ProxyGenerator.saveGeneratedFiles=true, which writes the generated .class files into the current directory, and open them with javap -c.

newProxyInstance also enforces a few rules, which a separate test confirmed on JDK 21. Passing a class instead of an interface fails with IllegalArgumentException: java.lang.String is not an interface, and listing the same interface twice fails with "repeated interface". When two interfaces declare the same method, such as String name() in both A and B, the proxy has one method, and the handler always receives the Method object of the first interface in the list, even when the call was made through B. A handler that dispatches on method.getDeclaringClass() must allow for that.

Ways to wrap behaviour around an object
TechniqueSinceWorks onBest for
Hand-written decoratorAny versionInterfaces or classesOne or two interfaces, maximum speed and clarity
Proxy + InvocationHandlerJava 1.3Interfaces onlyOne cross-cutting concern for many interfaces
InvocationHandler.invokeDefaultJava 16Default methods of proxied interfacesProxies of interfaces that contain logic
MethodHandleProxies.asInterfaceInstanceJava 7Single-method interfacesTurning a method handle into an interface object
Bytecode libraries (Byte Buddy, cglib)ExternalClasses and interfacesFrameworks 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.

Java
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:

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].
  • method.invoke(target, args) wraps any exception thrown by the target in InvocationTargetException. The handler unwraps it with getCause() and rethrows the original, so the caller caught a plain ArithmeticException exactly as without the proxy.
  • The object's class is a generated $Proxy class, and Proxy.isProxyClass recognizes it. The interfaces must be visible from the given class loader, which is why type.getClassLoader() is passed.

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.

Java
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:

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 method, such as @Retry(times = 3), to decide which calls may be repeated.
  • The configuration proxy answered host() and port() by looking the method name up in a map. No class implements AppConfig; Spring Data repositories and many configuration libraries work on the same principle.

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.

Java
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:

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
  1. The forwarding handler also forwarded toString and hashCode, so the proxy printed as "RealRepo" and had the target's hash code. But proxy.equals(proxy) was false: the call became target.equals(proxy), and the target is not equal to the proxy. Proxies put into a HashSet or used as map keys then misbehave. Handle the three Object methods explicitly, as the default-method example below does.
  2. Returning null from invoke for a method with a primitive return type, here int count(), throws NullPointerException when the proxy unboxes it.
  3. A checked exception that the interface method does not declare, such as IOException, cannot reach the caller as itself. The proxy wraps it in UndeclaredThrowableException. Unchecked exceptions and declared checked exceptions pass through unchanged.
  4. Forgetting to unwrap InvocationTargetException produced a double wrapping: the caller got UndeclaredThrowableException, whose cause is the InvocationTargetException, whose cause is the real "db down". Error handling written for the real exception type never sees it.

Self-invocation bypasses the proxy

An order service's placeOrder calls its own audit method. Both are on the proxied interface, and the handler announces every call it sees.

Java
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:

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 placeOrder was called through the proxy, the handler saw it, but the audit call made inside placeOrder did not appear: it was a plain call on this, the real object. Only the direct proxy.audit call passed through the handler.
  • This is the reason a Spring @Transactional or @Cacheable 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.

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() default method built from two getters shows the Java 16 solution and a correct treatment of equals, hashCode and toString.

Java
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:

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
  • InvocationHandler.invokeDefault(proxy, method, args) ran the interface's url() body on the proxy. Inside it, host() and port() were calls on the proxy and came back through the handler, giving "https://api.example.com:8443".
  • The handler answers the three Object methods itself: a readable toString, identity-based hashCode, and equals that compares the proxy with the argument. Now the proxy equals itself and behaves correctly in hash-based collections.
  • The values map is a TreeMap so that toString lists keys in the same order on every run; Map.of iteration order changes between JVM runs.

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. Best of 5 runs; a rough comparison, not a benchmark.

Java
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):

Output
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 Method.invoke, and unboxes the result.
  • 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 method on every call. Cache what it needs per Method in a map, as frameworks do.

Choosing a proxy technique

When to use a dynamic proxy
SituationUse
The same concern (logging, timing, retries) on many interfacesA dynamic proxy with one handler
Implementing an interface from metadata aloneA target-less proxy
A single interface, performance-sensitiveA hand-written decorator
Interfaces with default methodsInvocationHandler.invokeDefault (Java 16)
Proxying a concrete classA bytecode library, or extract an interface
Behaviour that must also apply to internal callsPut the logic in the class itself, or call through the proxy reference

Handlers rely on reflection; for faster dynamic dispatch see method handles, and for the decorator and proxy patterns in general see design patterns.