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.
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.
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();
}
}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.
Last updated: 1 November 2026
Previous question: How do default methods in interfaces affect the backward compatibility of a Java application?
Next question: Explain shallow copy vs deep copy in the context of Java cloning.