Java Dynamic Proxy: Intercept Method Calls With Proxy and InvocationHandler

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 240 of 306

A Java dynamic proxy is an object whose class is generated at runtime to implement one or more interfaces. Every method call on it is sent to a single InvocationHandler, which decides what to do: return a value, call a real object, log, cache or block the call.

Dynamic proxies let you add behavior around many methods without editing them. Spring uses them for @Transactional, Retrofit uses them to turn interfaces into HTTP clients, and Mockito-style tools use the same idea for mocks. This lesson builds on the Java Reflection API and finishes with a caching layer driven by an annotation.


Java Dynamic Proxy Syntax

A proxy needs three things: a class loader, the interfaces to implement, and a handler.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
        MyInterface.class.getClassLoader(),   // where to define the generated class
        new Class<?>[] {MyInterface.class},   // interfaces it implements
        handler);                             // receives every call

The handler has one method:

public interface InvocationHandler {
    Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}
ParameterMeaning
proxyThe proxy object the method was called on
methodThe interface Method that was called
argsThe arguments, boxed, or null for a method with no parameters
return valueBecomes the method's result; it is unboxed for primitive return types

Your First Dynamic Proxy

This proxy implements Greeter without any class that implements it. The handler answers each call itself.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Arrays;

interface Greeter {
    String greet(String name);
    int countLetters(String word);
}

public class FirstProxy {
    public static void main(String[] args) {
        InvocationHandler handler = (proxy, method, methodArgs) -> {
            System.out.println("Intercepted " + method.getName() + Arrays.toString(methodArgs));
            if (method.getName().equals("greet")) {
                return "Vanakkam, " + methodArgs[0] + "!";
            }
            if (method.getName().equals("countLetters")) {
                return ((String) methodArgs[0]).length();
            }
            throw new UnsupportedOperationException(method.getName());
        };

        Greeter greeter = (Greeter) Proxy.newProxyInstance(
                Greeter.class.getClassLoader(), new Class<?>[] {Greeter.class}, handler);

        System.out.println(greeter.greet("Asha"));
        System.out.println(greeter.countLetters("reflection"));
        System.out.println("Is proxy class? " + Proxy.isProxyClass(greeter.getClass()));
        System.out.println("Implements Greeter? " + (greeter instanceof Greeter));
    }
}

Output:

Intercepted greet[Asha]
Vanakkam, Asha!
Intercepted countLetters[reflection]
10
Is proxy class? true
Implements Greeter? true

How it works:

  • Proxy.newProxyInstance generates a new class at runtime that implements Greeter, then creates one instance of it.
  • Every call, such as greeter.greet("Asha"), becomes handler.invoke(proxy, greetMethod, new Object[] {"Asha"}).
  • countLetters returns int, so the handler returns an Integer and the proxy unboxes it. Returning null for a primitive return type would throw NullPointerException.
  • Proxy.isProxyClass confirms the class was generated by Proxy.

Wrapping a Real Object: A Logging Proxy

The most common pattern is delegation: the handler holds a real object, does some extra work and forwards the call with method.invoke. The caller cannot tell the difference, because the proxy implements the same interface.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

interface PaymentGateway {
    String charge(String customer, double amount);
    boolean refund(String transactionId);
}

class SimpleGateway implements PaymentGateway {
    private int nextId = 1;

    public String charge(String customer, double amount) {
        return "TXN-" + nextId++ + " charged " + amount + " to " + customer;
    }

    public boolean refund(String transactionId) {
        if (!transactionId.startsWith("TXN-")) {
            throw new IllegalArgumentException("unknown transaction " + transactionId);
        }
        return true;
    }
}

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("-> " + method.getName() + Arrays.toString(args));
        try {
            Object result = method.invoke(target, args); // forward to the real object
            System.out.println("<- " + method.getName() + " returned " + result);
            return result;
        } catch (InvocationTargetException e) {
            System.out.println("<- " + method.getName() + " threw " + e.getCause());
            throw e.getCause();                          // rethrow the real exception
        }
    }

    @SuppressWarnings("unchecked")
    static <T> T wrap(T target, Class<T> anInterface) {
        return (T) Proxy.newProxyInstance(anInterface.getClassLoader(),
                new Class<?>[] {anInterface}, new LoggingHandler(target));
    }
}

public class LoggingProxy {
    public static void main(String[] args) {
        PaymentGateway gateway = LoggingHandler.wrap(new SimpleGateway(), PaymentGateway.class);

        gateway.charge("Asha", 1499.0);
        gateway.refund("TXN-1");
        try {
            gateway.refund("ORDER-9");
        } catch (IllegalArgumentException e) {
            System.out.println("Caller caught: " + e.getMessage());
        }
    }
}

Output:

-> charge[Asha, 1499.0]
<- charge returned TXN-1 charged 1499.0 to Asha
-> refund[TXN-1]
<- refund returned true
-> refund[ORDER-9]
<- refund threw java.lang.IllegalArgumentException: unknown transaction ORDER-9
Caller caught: unknown transaction ORDER-9

How it works:

  • LoggingHandler stores the real SimpleGateway. The Method object it receives belongs to the PaymentGateway interface, and method.invoke(target, args) calls the matching implementation on the real object.
  • method.invoke wraps exceptions in InvocationTargetException. Rethrowing e.getCause() means the caller sees the original IllegalArgumentException, exactly as without the proxy.
  • The generic wrap method works for any interface, so the same logging can be added to every service in an application.

Object Methods and Default Methods in a Proxy

Calls to toString, equals and hashCode also go through the handler, because they are declared in Object. Default interface methods do too; since Java 16, InvocationHandler.invokeDefault runs their original body.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

interface Course {
    String title();

    default String label() {
        return "[" + title() + "]";
    }
}

public class SpecialMethods {
    public static void main(String[] args) {
        InvocationHandler handler = (proxy, method, methodArgs) -> {
            System.out.println("  handler: " + method.getDeclaringClass().getSimpleName() + "." + method.getName());
            if (method.isDefault()) {
                return InvocationHandler.invokeDefault(proxy, method, methodArgs);
            }
            return switch (method.getName()) {
                case "title" -> "Java Proxies";
                case "toString" -> "CourseProxy";
                case "hashCode" -> 42;
                case "equals" -> proxy == methodArgs[0];
                default -> throw new UnsupportedOperationException(method.getName());
            };
        };

        Course course = (Course) Proxy.newProxyInstance(
                Course.class.getClassLoader(), new Class<?>[] {Course.class}, handler);

        System.out.println(course.label());
        System.out.println(course.toString());
        System.out.println(course.hashCode());
        System.out.println(course.equals(course));
        System.out.println("getClass() is not proxied: " + course.getClass().getSimpleName().startsWith("$Proxy"));
    }
}

Output:

  handler: Course.label
  handler: Course.title
[Java Proxies]
  handler: Object.toString
CourseProxy
  handler: Object.hashCode
42
  handler: Object.equals
true
getClass() is not proxied: true

How it works:

  • label() is a default method, so the handler calls invokeDefault. Its body calls title() on the proxy, which comes back through the handler a second time.
  • toString, hashCode and equals arrive with Object as their declaring class. A proxy that forgets to handle them breaks println, HashMap keys and equality checks.
  • getClass() is final in Object, so it is never sent to the handler. It returns the generated class, whose name starts with $Proxy.

Exceptions From a Java Dynamic Proxy

A handler can throw any exception, but the interface method may not declare it. Unchecked exceptions pass through unchanged. A checked exception that the interface method does not declare is wrapped in UndeclaredThrowableException.

import java.io.IOException;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

interface FileStore {
    String read(String path);                         // no throws clause
    String readChecked(String path) throws IOException;
}

public class ProxyExceptions {
    public static void main(String[] args) {
        FileStore store = (FileStore) Proxy.newProxyInstance(
                FileStore.class.getClassLoader(), new Class<?>[] {FileStore.class},
                (proxy, method, methodArgs) -> {
                    throw new IOException("disk not mounted: " + methodArgs[0]);
                });

        try {
            store.read("/data/marks.csv");
        } catch (UndeclaredThrowableException e) {
            System.out.println("read        -> " + e.getClass().getSimpleName() + ", cause: " + e.getCause());
        }

        try {
            store.readChecked("/data/marks.csv");
        } catch (IOException e) {
            System.out.println("readChecked -> " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}

Output:

read        -> UndeclaredThrowableException, cause: java.io.IOException: disk not mounted: /data/marks.csv
readChecked -> IOException: disk not mounted: /data/marks.csv

How it works:

  • read does not declare IOException, so the proxy cannot throw it directly. It wraps it in the unchecked UndeclaredThrowableException.
  • readChecked declares throws IOException, so the same exception reaches the caller unchanged.

Proxy Limitations

LimitationDetails
Interfaces onlyProxy cannot extend a class. Libraries such as Byte Buddy generate subclasses when there is no interface.
Same instance onlyA call from inside the real object to its own methods (this.method()) does not pass through the proxy.
Reflection costEach call goes through invoke with boxing and an argument array, so it is slower than a direct call.
Final Object methodsgetClass, wait, notify and notifyAll are never intercepted.

Note: The "same instance" limit explains a well-known Spring surprise: a @Transactional method called from another method of the same class runs without a transaction, because the call never leaves the real object.


Real-World Example: An Annotation-Driven Caching Proxy

This example combines a custom annotation, as in Java Custom Annotations, with a dynamic proxy. Methods marked @Cacheable on a repository interface are cached; any other method is treated as a write and clears the cache. The repository class itself contains no caching code at all.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// ---------- the annotation ----------
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Cacheable { }

// ---------- the interface with caching rules ----------
interface CourseRepository {
    @Cacheable
    String findTitle(int courseId);

    @Cacheable
    List<String> findLessons(int courseId);

    void rename(int courseId, String newTitle);
}

// ---------- the real, slow implementation ----------
class DatabaseCourseRepository implements CourseRepository {
    int queries = 0;
    private final Map<Integer, String> titles = new HashMap<>(Map.of(101, "Java Basics", 202, "Java Reflection"));

    public String findTitle(int courseId) {
        queries++;
        return titles.get(courseId);
    }

    public List<String> findLessons(int courseId) {
        queries++;
        return courseId == 202
                ? List.of("Reflection API", "Class Metadata", "Proxy Basics")
                : List.of("Variables", "Loops");
    }

    public void rename(int courseId, String newTitle) {
        queries++;
        titles.put(courseId, newTitle);
    }
}

// ---------- the caching handler ----------
class CachingHandler implements InvocationHandler {
    private final Object target;
    private final Map<List<Object>, Object> cache = new HashMap<>();
    int hits = 0;
    int misses = 0;

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

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass() == Object.class) {
            return callTarget(method, args);                  // toString, equals, hashCode
        }
        if (!method.isAnnotationPresent(Cacheable.class)) {
            cache.clear();                                    // a write invalidates cached reads
            System.out.println("  [write] " + method.getName() + " -> cache cleared");
            return callTarget(method, args);
        }

        List<Object> key = new ArrayList<>();
        key.add(method.getName());
        key.addAll(Arrays.asList(args));
        if (cache.containsKey(key)) {
            hits++;
            System.out.println("  [hit]   " + key);
            return cache.get(key);
        }
        misses++;
        System.out.println("  [miss]  " + key);
        Object result = callTarget(method, args);
        cache.put(key, result);
        return result;
    }

    private Object callTarget(Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(target, args);
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    }
}

public class CachingProxy {
    public static void main(String[] args) {
        DatabaseCourseRepository database = new DatabaseCourseRepository();
        CachingHandler handler = new CachingHandler(database);
        CourseRepository repository = (CourseRepository) Proxy.newProxyInstance(
                CourseRepository.class.getClassLoader(), new Class<?>[] {CourseRepository.class}, handler);

        System.out.println(repository.findTitle(202));
        System.out.println(repository.findTitle(202));
        System.out.println(repository.findLessons(202));
        System.out.println(repository.findLessons(202));
        System.out.println(repository.findTitle(101));
        repository.rename(202, "Advanced Java Reflection");
        System.out.println(repository.findTitle(202));

        System.out.printf("database queries=%d, cache hits=%d, misses=%d%n",
                database.queries, handler.hits, handler.misses);
    }
}

Output:

  [miss]  [findTitle, 202]
Java Reflection
  [hit]   [findTitle, 202]
Java Reflection
  [miss]  [findLessons, 202]
[Reflection API, Class Metadata, Proxy Basics]
  [hit]   [findLessons, 202]
[Reflection API, Class Metadata, Proxy Basics]
  [miss]  [findTitle, 101]
Java Basics
  [write] rename -> cache cleared
  [miss]  [findTitle, 202]
Advanced Java Reflection
database queries=5, cache hits=2, misses=4

How it works:

  1. Rules live on the interface. @Cacheable is written on the CourseRepository methods. The handler receives the interface's Method object, so method.isAnnotationPresent(Cacheable.class) sees those annotations directly.
  2. Cache key. The key is a list of the method name followed by the arguments, such as [findTitle, 202]. List implements equals and hashCode by content, so equal calls produce equal keys. ArrayList is used because it allows null arguments, unlike List.of.
  3. Hits and misses. The second findTitle(202) and findLessons(202) are answered from the map, so the database is never touched.
  4. Invalidation. rename has no @Cacheable, so the handler treats it as a write and clears the cache. The next findTitle(202) misses and returns the new title instead of stale data.
  5. Object methods. Calls declared by Object are forwarded straight to the real object, so toString and equals behave normally.
  6. The result. Seven repository calls cost only five database queries. The same handler would cache any interface marked with @Cacheable, which is how Spring's @Cacheable works behind the scenes.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Dynamic Proxy: Intercept Method Calls With Proxy and InvocationHandler and get answers drawn from it.

Signed-in readers only.