Clean • Professional
Dynamic Proxy allows you to create objects at runtime that can intercept method calls and add extra behavior.
It is a powerful feature in Java that works with interfaces and is commonly used in frameworks to implement cross-cutting concerns like logging, security, and transactions.
In simple words: You can add extra logic (like logging, security, or transactions) without modifying the original class.

InvocationHandler is an interface that handles method calls on proxy objects.
It acts as the core component where you can define custom behavior that runs whenever a method is invoked on the proxy.
Example:
import java.lang.reflect.*;
class MyHandler implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Method called: " + method.getName());
return null;
}
}
Explanation
invoke() method is automatically called whenever a method is invoked on the proxy objectmethod.getName() → Gets the name of the method being calledKey Points
invoke() runs whenever a method is calledProxy objects are created using Proxy.newProxyInstance().
This method creates a dynamic proxy object at runtime, which uses an InvocationHandler to handle method calls.
Example:
import java.lang.reflect.*;
interface Service {
void execute();
}
public class Main {
public static void main(String[] args) {
Service proxy = (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class[]{Service.class},
new MyHandler()
);
proxy.execute();
}
}
Output
Methodcalled:execute
Explanation
Proxy.newProxyInstance() → Creates a proxy object at runtimeService.class.getClassLoader() → Loads the interface classnew Class[]{Service.class} → Defines which interfaces the proxy will implementnew MyHandler() → Handles method calls using InvocationHandlerKey Points

Dynamic proxies are heavily used in frameworks like Spring for AOP (Aspect-Oriented Programming).
They help in adding extra functionality without modifying the original business logic.
What happens:
Example Flow:
UserService.save()
↓
Proxy intercepts method call
↓
InvocationHandler.invoke()
↓
Before Logic executes
→ Logging start
→ Security checks
→ Transaction begin
↓
Actual Method Execution
→ method.invoke(target, args)
↓
After Logic executes
→ Transaction commit / rollback
→ Success / Error logging
↓
Return result to Proxy
↓
Proxy returns response to User
Common Use Cases:

Dynamic Proxies play an important role in modern Java development by allowing developers to add behavior dynamically at runtime.