Background:
The Dynamic Proxy Pattern appeared in Java 1.3 and allowed the implementation of AOP patterns, logging, security, and dynamic code generation without manually writing proxy classes. This became very popular in Spring, Hibernate, and other frameworks.
Problem:
Sometimes it is necessary to add functionality to an existing interface or change the behavior of methods at runtime without modifying the source code. Example: logging each method call, access checks, profiling. The main problem is the inability to do this "manually" for all classes, especially if there are many classes or they are generated dynamically.
Solution:
Java provides a standard API in the java.lang.reflect package for creating proxy objects "on the fly" for any interfaces using Proxy.newProxyInstance. An InvocationHandler object is implemented, which receives each method call and implements its logic.
Example code:
import java.lang.reflect.*; interface Service { void serve(); } class ServiceImpl implements Service { public void serve() { System.out.println("Serving..."); } } class LoggingHandler implements InvocationHandler { private final Object target; public LoggingHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Calling " + method.getName()); return method.invoke(target, args); } } Service service = (Service) Proxy.newProxyInstance( Service.class.getClassLoader(), new Class[]{Service.class}, new LoggingHandler(new ServiceImpl())); service.serve();
Key features:
Can a standard dynamic proxy "wrap" a regular class that does not implement interfaces?
No. Dynamic Proxy works only with interfaces. For classes, bytecode manipulation is needed (such as CGLIB).
What happens if an interface contains methods with return types incompatible with the return value from InvocationHandler?
A ClassCastException will be thrown, so the return value must be strictly compatible with the definition of the interface.
Can dynamic proxy be used for final methods?
No. The Proxy works only at the interface level, where there are no final methods. Final methods cannot be overridden at all.
Negative case
A developer attempted to implement audit logging through Proxy on classes without an interface.
Pros:
Cons:
Positive case
An interface was defined for the contract, and a proxy wrapper was created for it.
Pros:
Cons: