Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Interview Questions Java Java and Cryptography Interview Series Java Programming Java Tutorial Module 27 - Java Advanced and JVM Internals

Java Reflection Dynamic Proxy for AOP Interceptors

Reviewed & accurate
AI Summary

Introduction

The Java Reflection dynamic proxy API shipped in May 2000 as part of Java 1.3. The java.lang.reflect.Proxy class lets you create an implementation of one or more interfaces at runtime without writing the implementation class by hand. The Proxy.newProxyInstance method takes a ClassLoader, an array of interfaces, and an InvocationHandler, and returns an object that implements all the interfaces and dispatches every method call to the handler's invoke method. For a Java learner, Java Reflection dynamic proxy is the modern foundation of aspect-oriented programming (AOP), remote method invocation (RMI), and ORM lazy-loading. Interviewers ask about dynamic proxies because they reveal whether a candidate understands the relationship between interfaces, bytecode, and runtime method dispatch, and because every modern Java framework (Spring AOP, Hibernate, Mockito) is built on top of dynamic proxies or their bytecode-weaving cousins (CGLIB, ByteBuddy).

Understanding Java Reflection dynamic proxy also clarifies the difference between JDK proxies (interface-only, generated at runtime by the JVM), CGLIB proxies (subclass any class, generated by bytecode manipulation), and the static-factory pattern (hand-written wrappers). The choice between these three is a real engineering decision in every service-side Java codebase: Spring AOP uses JDK proxies by default when the target has an interface, falling back to CGLIB when it does not; Hibernate uses Javassist (a CGLIB-like library) for entity lazy-loading; Mockito uses both, depending on whether the mocked type is a class or an interface.

What is Java Reflection Dynamic Proxy?

Java Reflection dynamic proxy is a runtime-generated class that implements one or more interfaces and forwards every method call to an InvocationHandler. The proxy class itself is generated by the JVM at runtime; you do not write its source. The InvocationHandler is a single-method interface: invoke(Object proxy, Method method, Object[] args) receives the proxy instance, the Method being called, and the Object array of arguments; it can inspect them, modify them, delegate to a real target, or short-circuit with its own return value. Java Reflection dynamic proxy belongs to the reflection and metaprogramming category of java.lang.reflect. It is different from CGLIB and ByteBuddy proxies in that JDK dynamic proxies can only proxy interfaces, not classes; CGLIB and ByteBuddy subclass the target class at bytecode level. It is different from RMI stubs in that the handler runs in the same JVM as the caller; RMI stubs marshal and dispatch over the network.

The proxy class generated by Proxy.newProxyInstance is named something like com.sun.proxy.$Proxy0 and is loaded into the same ClassLoader that loaded the interfaces. The generated class's methods are all bridge-like: each method is a tiny stub that immediately calls handler.invoke with itself as the first argument, the Method object for the called method, and the arguments array. Because the JVM caches the generated proxy class per (ClassLoader, interfaces) tuple, repeated Proxy.newProxyInstance calls with the same interfaces reuse the cached class and only allocate a new instance.

How Java Reflection Dynamic Proxy Works - Step by Step

Step 1: The interfaces. You define one or more interfaces that the proxy should implement. The proxy class will implement all of them. You cannot proxy a concrete class with JDK dynamic proxies; you can only proxy interfaces. If you need to proxy a concrete class, use CGLIB or ByteBuddy, which generate a subclass at bytecode level.

Step 2: The InvocationHandler. You write a class that implements InvocationHandler. The invoke(Object proxy, Method method, Object[] args) method is the single entry point: every method call on the proxy is dispatched here. The handler typically delegates to a real target after applying interceptors (logging, transactions, security). The handler must be careful not to call any method on the proxy argument itself, because that would recurse into the handler.

Step 3: The Proxy.newProxyInstance call. You pass the ClassLoader (typically the interface's class loader), the interface array, and the handler. The JVM generates a new class (named something like $Proxy0) that implements all the interfaces; the generated class's methods all call handler.invoke. The newProxyInstance call returns an instance of the generated class. Subsequent calls with the same (ClassLoader, interfaces) tuple reuse the cached proxy class.

Step 4: Method dispatch. When the caller invokes proxy.someMethod(args), the JVM dispatches to the generated class's someMethod, which immediately calls handler.invoke(proxy, Method.someMethod, args). The handler can inspect the Method, apply before-advice, call method.invoke(target, args), apply after-advice, and return the result. The Method object is shared with the rest of the JVM and reflects the interface method, not the proxy's stub.

Step 5: Exception handling. If method.invoke(target, args) throws, the InvocationTargetException is thrown by the reflection runtime; the handler typically unwraps it (e.getCause()) to rethrow the original exception. The handler can also catch and convert (e.g., translate SQLException to a domain exception, or wrap an unchecked exception in a retry policy). Checked exceptions declared by the interface method are propagated cleanly; checked exceptions not declared by the interface are tricky (UndeclaredThrowableException is thrown by the proxy to wrap them).

Step 6: Performance considerations. JDK dynamic proxies use reflection, which has measurable overhead. Modern JVMs optimise the common case (Method.invoke is inlined after enough warm-up, and the generated proxy class's stubs are short and easy to inline). For high-throughput code, ByteBuddy or CGLIB generate direct bytecode that avoids reflection entirely; the call site dispatches via a regular invokevirtual to a generated subclass method. The choice between JDK proxies and bytecode-generation proxies is the choice between "interface-only, zero dependencies" and "subclass any class, faster dispatch".

Java Program for Java Reflection Dynamic Proxy for AOP Interceptors

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 DynamicProxyDemo {

    // The interface our proxy will implement.
    interface Calculator {
        int add(int a, int b);
        int sub(int a, int b);
    }

    // The real implementation we want to wrap with an aspect.
    static class CalculatorImpl implements Calculator {
        public int add(int a, int b) { return a + b; }
        public int sub(int a, int b) { return a - b; }
    }

    // An InvocationHandler that logs every call (a "before" advice
    // and an "after" advice) and delegates to the real target.
    static class LoggingHandler implements InvocationHandler {
        private final Object target;

        LoggingHandler(Object target) { this.target = target; }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            System.out.println("[before] " + method.getName()
                + " args=" + Arrays.toString(args));
            Object result;
            try {
                result = method.invoke(target, args);
            } catch (InvocationTargetException e) {
                throw e.getCause();
            }
            System.out.println("[after]  " + method.getName()
                + " result=" + result);
            return result;
        }
    }

    public static void main(String[] args) {
        Calculator real = new CalculatorImpl();
        Calculator proxy = (Calculator) Proxy.newProxyInstance(
            Calculator.class.getClassLoader(),
            new Class<?>[] { Calculator.class },
            new LoggingHandler(real));

        System.out.println("add(2,3) = " + proxy.add(2, 3));
        System.out.println("sub(10,4) = " + proxy.sub(10, 4));

        // Inspect the generated proxy class name.
        System.out.println("proxy class name: "
            + proxy.getClass().getName());
    }
}

Code Explanation - Line by Line

The Calculator interface declares two methods, add and sub. The CalculatorImpl class implements them with trivial arithmetic. The LoggingHandler is the InvocationHandler that wraps any target object: it receives the method name and the arguments, prints a "[before]" line, calls method.invoke(target, args) to delegate to the real implementation, prints an "[after]" line, and returns the result. The InvocationTargetException catch is the standard idiom for unwrapping reflection's exception wrapping; without it, the caller would receive an InvocationTargetException instead of the real exception the target threw.

The main method creates the real CalculatorImpl, then creates a proxy via Proxy.newProxyInstance. The first argument is the ClassLoader (we use the one that loaded the Calculator interface); the second is an array of Class objects representing the interfaces the proxy should implement (here, just Calculator); the third is the InvocationHandler wrapping the real implementation. The return value is cast to Calculator because the proxy implements it; the cast is unchecked at runtime (because of erasure), but the proxy does implement Calculator so the cast succeeds.

When proxy.add(2, 3) is called, the JVM dispatches to the generated $Proxy0 class's add method, which immediately calls handler.invoke(proxy, the Method object for add, new Object[] {2, 3}). The handler prints the [before] line, calls method.invoke(real, args) which returns 5, prints the [after] line, and returns 5. The caller's println receives 5 and prints "add(2,3) = 5". The same flow happens for sub(10, 4), with the [before] and [after] lines bracketing the call to the real CalculatorImpl.sub method.

The final println inspects the proxy's class name. The output is something like "com.sun.proxy.$Proxy0" on HotSpot, "jdk.proxy1.$Proxy0" on JDK 17+, or similar on other JVMs. The exact name is an implementation detail, but the dollar-and-Proxy prefix is the convention. The class is generated lazily on the first Proxy.newProxyInstance call for this interface tuple, then cached and reused.

Interview Questions and Answers

Q1. What is a Java dynamic proxy and what is its primary use case?

A Java dynamic proxy is a runtime-generated class that implements one or more interfaces and forwards every method call to an InvocationHandler. The primary use case is AOP: logging, transactions, security, caching, and remote-call dispatch. Spring AOP uses JDK dynamic proxies for interface-based beans; Hibernate uses them for lazy-loading entity associations; Mockito uses them for mocking interfaces in unit tests. The proxy class is generated by Proxy.newProxyInstance at runtime, so you do not write the proxy's source code by hand.

Q2. What is the difference between JDK dynamic proxies and CGLIB / ByteBuddy proxies?

JDK dynamic proxies can only proxy interfaces; the proxy class implements the interface and dispatches via InvocationHandler. CGLIB and ByteBuddy generate a subclass of the target class at bytecode level, so they can proxy concrete classes without interfaces. JDK proxies have zero external dependencies but use reflection for every call; CGLIB and ByteBuddy generate direct bytecode so dispatch is faster. Spring AOP uses JDK proxies by default when the target has an interface, falling back to CGLIB when it does not.

Q3. Why does the InvocationHandler.invoke method receive the proxy object as its first argument?

The proxy argument is the runtime instance of the generated proxy class, useful when the handler needs to pass the proxy to another component (e.g., for self-invocation or for caching the proxy identity). It is rarely used directly in business logic because calling a method on it would recurse into the handler (infinite loop). The argument exists so the handler can identify which proxy instance the call came from, which matters when one handler is shared by multiple proxy instances.

Q4. What happens if you call method.invoke(proxy, args) inside the handler instead of method.invoke(target, args)?

You get infinite recursion. The proxy's method dispatches back to the handler's invoke, which calls method.invoke on the proxy again, and so on until StackOverflowError. Always invoke on the real target, not the proxy, when you want to delegate. This is the most common mistake when writing InvocationHandlers, especially for handlers that want to call other methods on the same proxy (like a transactional handler calling a helper method on this).

Q5. How do you handle checked exceptions thrown by the target method?

Method.invoke wraps any exception the target throws in InvocationTargetException. Inside the handler, catch InvocationTargetException, call e.getCause() to recover the original exception, and rethrow it. If the original is a checked exception declared by the interface method, the proxy propagates it cleanly. If it is a checked exception not declared by the interface, the proxy wraps it in an UndeclaredThrowableException; the standard workaround is to ensure the interface declares every checked exception the implementation can throw.

Q6. What is the lifecycle of a dynamically-generated proxy class?

The JVM generates the proxy class lazily on the first newProxyInstance call for a given (ClassLoader, interfaces) tuple. Subsequent calls with the same tuple reuse the cached proxy class; only a new instance is allocated. The proxy class lives in the JVM's metaspace (or permgen in older JVMs) and is garbage-collected when its ClassLoader is unreachable. The proxy instance is garbage-collected when no references to it remain, like any other object. In a long-running container (Spring, JBoss), the proxy classes accumulate in metaspace; if many are generated for distinct interface tuples, this can lead to metaspace pressure.

Q7. You are designing a service layer where every method should be wrapped with a transaction-begin and transaction-commit aspect. The services are interfaces. Would you use JDK dynamic proxies or CGLIB, and how would you structure the handler?

Use JDK dynamic proxies because the services are interfaces; there is no need for CGLIB subclassing. The handler would begin a transaction in a try block, call method.invoke(target, args), commit the transaction in the try block, and roll back in the catch. The handler must be careful to handle self-invocation: a method on the target calling another method on the target through this will bypass the proxy because it is a direct call, not a proxy call, so the transaction aspect will not fire. To avoid self-invocation pitfalls, inject the proxy instance into the target bean (via @Resource or self-injection) and have the target call its dependencies through the proxy, not through this. This is the standard Spring @Transactional pattern.

Sample Input and Output

Input: CalculatorImpl real target with add(2,3) and sub(10,4).
       LoggingHandler wrapping real with before/after advice.
       Proxy.newProxyInstance creating a $Proxy0 implementing Calculator.

Output:
[before] add args=[2, 3]
[after]  add result=5
add(2,3) = 5
[before] sub args=[10, 4]
[after]  sub result=6
sub(10,4) = 6
proxy class name: com.sun.proxy.$Proxy0

The output confirms four behaviours: each call to the proxy dispatched through the LoggingHandler's invoke method; the [before] advice printed the method name and arguments before delegating to the real CalculatorImpl; the [after] advice printed the method name and result after the real implementation returned; and the proxy class name matches the HotSpot convention of com.sun.proxy.$ProxyN for the first generated proxy class. The exact proxy class name is JVM-dependent; JDK 17+ uses the jdk.proxy1 or jdk.proxy2 prefix, but the dollar-Proxy convention is consistent.

Common Mistakes to Avoid

First, calling method.invoke(proxy, args) inside the handler. This causes infinite recursion because the proxy's method dispatches back to the handler. Always invoke on the real target. This is the most common InvocationHandler bug and is hard to debug because the symptom is a StackOverflowError with no obvious cause.

Second, expecting the proxy to subclass a concrete class. JDK dynamic proxies implement interfaces only; they cannot subclass a class. If you need to proxy a class, use CGLIB or ByteBuddy, which generate a subclass at bytecode level. Spring AOP falls back to CGLIB automatically when the target has no interface; the configuration is spring.aop.proxy-target-class=true.

Third, forgetting to unwrap InvocationTargetException. If method.invoke(target, args) throws, the wrapped exception is InvocationTargetException; if you do not unwrap, the caller sees a confusing reflection exception instead of the real cause. The standard idiom is to catch InvocationTargetException, call e.getCause(), and rethrow the cause.

Fourth, sharing a single InvocationHandler across multiple proxy instances when the handler holds per-instance state. Each proxy instance needs its own handler (or the handler must dispatch on the proxy argument) to avoid cross-instance contamination. Use a handler factory that creates a new handler per target, or use a Map from proxy instance to per-instance state inside the handler.

Real-World Applications

Java Reflection dynamic proxies are the backbone of Java's enterprise frameworks. Spring Framework's AOP uses JDK dynamic proxies for interface-based beans; the @Transactional, @Async, @Cacheable, and @Secured annotations are all implemented as InvocationHandler interceptors that wrap the target bean. Hibernate uses dynamic proxies (or Javassist, a CGLIB-like library) for lazy-loading entity associations: when you call customer.getOrders(), the proxy fetches the orders from the database on first access. Mockito uses dynamic proxies to mock interfaces in unit tests; the when(...).thenReturn(...) DSL is built on a proxy that records invocations.

In the standards world, JAX-RS client proxies (JerseyClient.target(...).proxy(MyApi.class)) use dynamic proxies to convert interface method calls into HTTP requests. JPA's EntityManagerFactory.unwrap and JNDI lookup proxies both use dynamic proxies to forward calls to the real underlying implementation. In the testing world, EasyMock, jMock, and Spring's RestTemplate ClientHttpRequestInterceptor all use dynamic proxies for mock-object and HTTP-client implementations. The Spring Boot Actuator endpoints are also exposed via dynamic proxy wrappers that apply security and audit advice.

Conclusion

Java Reflection dynamic proxies are the foundation of aspect-oriented programming and remote method invocation in Java. The Proxy.newProxyInstance API generates a class at runtime that implements one or more interfaces and forwards every call to an InvocationHandler. We walked through the InvocationHandler contract, the method-dispatch flow, the InvocationTargetException unwrap idiom, and the self-invocation pitfall. To go deeper, study the Spring AOP source code for the JdkDynamicAopProxy class, then read the CGLIB and ByteBuddy documentation for the bytecode-weaving alternative. After that, the natural next topics are the Java Instrumentation API (which lets you weave bytecode at JVM startup) and the java.lang.invoke.MethodHandle (the low-level method-dispatch primitive that is faster than Method.invoke for hot paths).

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments