Dynamic Proxies in Java allow proxy objects to be created at runtime for one or more interfaces without writing separate proxy classes. They intercept method calls and delegate them through an InvocationHandler, making it possible to add additional behavior such as logging, security checks, caching, auditing, or transaction management without modifying the original implementation.
Key Points: • Dynamic proxies work only with interfaces and are created at runtime using the Proxy class. • All method invocations are routed through an InvocationHandler, which can execute custom logic before or after the actual method call. • They are widely used in frameworks such as Spring, Hibernate, and AOP implementations for cross-cutting concerns.
Example: Suppose a banking application has a TransferService interface. A dynamic proxy can intercept every transfer request to log transaction details and validate permissions before invoking the actual service implementation.
Code Example:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface PaymentService {
void processPayment();
}
class PaymentServiceImpl
implements PaymentService {
@Override
public void processPayment() {
System.out.println(
"Payment Processed");
}
}
class LoggingHandler
implements InvocationHandler {
private final Object target;
public LoggingHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(
"Before Method Call");
Object result =
method.invoke(target, args);
System.out.println(
"After Method Call");
return result;
}
}
public class DynamicProxyDemo {
public static void main(String[] args) {
PaymentService service =
new PaymentServiceImpl();
PaymentService proxy =(PaymentService) Proxy.newProxyInstance( service.getClass() .getClassLoader(),
new Class<?>[]{
PaymentService.class
},
new LoggingHandler(service));
proxy.processPayment();
}
}Interview Tip: A concise interview answer is: Dynamic Proxies create proxy objects for interfaces at runtime and intercept method calls through an InvocationHandler. They are commonly used to implement logging, security, transaction management, and AOP features without changing the original business code.