Dynamic Proxies and AOP
What you'll learn: How to create runtime proxy objects that intercept method calls to add cross-cutting concerns like logging and transactions without modifying original code.
What Are Dynamic Proxies?
Dynamic proxies are objects created at runtime that act as stand-ins for real objects. When you call a method on a proxy, it intercepts that call, lets you execute custom code (like logging), then forwards the call to the real object. Think of a proxy as a receptionist who logs every visitor before letting them through to the actual office.
This technique powers Aspect-Oriented Programming (AOP), which separates cross-cutting concerns (logging, security, transactions) from business logic. Instead of cluttering every method with logger.info() calls, you add logging once in the proxy.
How Java Dynamic Proxies Work
Java's java.lang.reflect.Proxy class creates proxies for interfaces. You provide:
- An interface the proxy should implement
- An
InvocationHandlerthat intercepts all method calls
Every method invocation on the proxy goes through the handler's invoke() method, where you can add pre-processing (logging entry), call the real method reflectively, and post-processing (logging exit).
InvocationHandler handler = (proxy, method, args) -> {
System.out.println("Before: " + method.getName());
Object result = method.invoke(realObject, args);
System.out.println("After: " + method.getName());
return result;
};
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class<?>[]{MyInterface.class},
handler
);
Now every method call on proxy automatically logs before and after execution—no changes to the original class needed!
Real-World Applications
Frameworks like Spring use proxies extensively for transactions (@Transactional), security checks, and caching. The proxy wraps your service objects and adds behavior declaratively.
Key Takeaway: Dynamic proxies use reflection to intercept method calls at runtime, enabling AOP patterns that cleanly separate cross-cutting concerns from core business logic.