0Pricing
Java Academy · Lesson

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 LoggingHandler

All lessons in this course

  1. Class Inspection with Reflection
  2. Invoking Methods and Accessing Fields
  3. Dynamic Proxies with InvocationHandler
  4. Reflection Performance and Alternatives
← Back to Java Academy