Java Dynamic Proxy: Intercept Method Calls With Proxy and InvocationHandler
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;
}
| Parameter | Meaning |
|---|---|
proxy | The proxy object the method was called on |
method | The interface Method that was called |
args | The arguments, boxed, or null for a method with no parameters |
| return value | Becomes 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.newProxyInstancegenerates a new class at runtime that implementsGreeter, then creates one instance of it.- Every call, such as
greeter.greet("Asha"), becomeshandler.invoke(proxy, greetMethod, new Object[] {"Asha"}). countLettersreturnsint, so the handler returns anIntegerand the proxy unboxes it. Returningnullfor a primitive return type would throwNullPointerException.Proxy.isProxyClassconfirms the class was generated byProxy.
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:
LoggingHandlerstores the realSimpleGateway. TheMethodobject it receives belongs to thePaymentGatewayinterface, andmethod.invoke(target, args)calls the matching implementation on the real object.method.invokewraps exceptions inInvocationTargetException. Rethrowinge.getCause()means the caller sees the originalIllegalArgumentException, exactly as without the proxy.- The generic
wrapmethod 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 callsinvokeDefault. Its body callstitle()on the proxy, which comes back through the handler a second time.toString,hashCodeandequalsarrive withObjectas their declaring class. A proxy that forgets to handle them breaksprintln,HashMapkeys and equality checks.getClass()isfinalinObject, 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:
readdoes not declareIOException, so the proxy cannot throw it directly. It wraps it in the uncheckedUndeclaredThrowableException.readCheckeddeclaresthrows IOException, so the same exception reaches the caller unchanged.
Proxy Limitations
| Limitation | Details |
|---|---|
| Interfaces only | Proxy cannot extend a class. Libraries such as Byte Buddy generate subclasses when there is no interface. |
| Same instance only | A call from inside the real object to its own methods (this.method()) does not pass through the proxy. |
| Reflection cost | Each call goes through invoke with boxing and an argument array, so it is slower than a direct call. |
Final Object methods | getClass, wait, notify and notifyAll are never intercepted. |
Note: The "same instance" limit explains a well-known Spring surprise: a
@Transactionalmethod 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:
- Rules live on the interface.
@Cacheableis written on theCourseRepositorymethods. The handler receives the interface'sMethodobject, somethod.isAnnotationPresent(Cacheable.class)sees those annotations directly. - Cache key. The key is a list of the method name followed by the arguments, such as
[findTitle, 202].ListimplementsequalsandhashCodeby content, so equal calls produce equal keys.ArrayListis used because it allowsnullarguments, unlikeList.of. - Hits and misses. The second
findTitle(202)andfindLessons(202)are answered from the map, so the database is never touched. - Invalidation.
renamehas no@Cacheable, so the handler treats it as a write and clears the cache. The nextfindTitle(202)misses and returns the new title instead of stale data. - Object methods. Calls declared by
Objectare forwarded straight to the real object, sotoStringandequalsbehave normally. - 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@Cacheableworks behind the scenes.