Dynamic Proxies with InvocationHandler
Create JDK dynamic proxies to intercept interface method calls for logging, caching, and retry.
What Is a Dynamic Proxy?
A JDK dynamic proxy is an object created at runtime that implements one or more interfaces. All method calls are forwarded to an InvocationHandler that you provide.
Creating a Proxy with Proxy.newProxyInstance
Call Proxy.newProxyInstance(classLoader, interfaces[], handler) to create a proxy. The proxy implements all the listed interfaces.
UserService proxy = (UserService) Proxy.newProxyInstance(
UserService.class.getClassLoader(),
new Class[]{UserService.class},
new LoggingHandler(realService)
);
proxy.findById(42L); // intercepted by LoggingHandlerAll lessons in this course
- Class Inspection with Reflection
- Invoking Methods and Accessing Fields
- Dynamic Proxies with InvocationHandler
- Reflection Performance and Alternatives