All topics
library
advanced

Proxy Pattern & Dynamic Proxies

Use java.lang.reflect.Proxy for runtime interface implementation and understand how frameworks use it.

The Proxy pattern provides a surrogate or placeholder for another object. Java supports dynamic proxies — creating interface implementations at runtime without pre-written classes.

Dynamic proxy = a personal assistant who answers your phone. Callers (clients) think they're talking to you (real object). The assistant (proxy) can screen calls (security), take notes (logging), or forward them to you (delegation).

Key Concepts

1
java.lang.reflect.Proxy: - Creates a proxy instance that implements specified interfaces - All method calls are intercepted by an InvocationHandler - The handler decides what to do: delegate, modify, log, cache, etc.
2
Used extensively by frameworks: - Spring AOP: @Transactional, @Cacheable, @Async — all implemented via dynamic proxies - JPA/Hibernate: lazy loading of entity relationships - Mockito: mock objects that record and verify method calls - RPC: remote method invocation proxies
3
Limitation: Proxy.newProxyInstance() only works with interfaces, not concrete classes. For class-based proxies, frameworks use: - CGLIB: generates subclass proxies via bytecode generation - ByteBuddy: modern bytecode generation library - Spring defaults to CGLIB for class-based proxies
4
Java dynamic proxies are simpler and require no external libraries, but are limited to interfaces. Most Spring-managed beans use interface-based proxies when possible.