Master Java Dynamic Proxies: Step‑by‑Step Implementation and Example

This article explains the concept, implementation steps, and a complete code example of Java dynamic proxies, showing how to define interfaces, create InvocationHandler, generate proxy instances with Proxy.newProxyInstance, and observe method‑level logging.

Architect Chen
Architect Chen
Architect Chen
Master Java Dynamic Proxies: Step‑by‑Step Implementation and Example

Dynamic proxy is a technique that generates proxy classes at runtime, allowing behavior control over target objects without modifying them.

What is a dynamic proxy

A dynamic proxy creates a proxy class during execution, enabling interception of method calls on the target object.

Java dynamic proxy

Java provides a built‑in dynamic proxy mechanism based on reflection. It can generate proxy classes for interfaces at runtime; CGLib can be used for class‑based proxies.

Implementation principle

Java dynamic proxy relies on the reflection API and follows these steps:

Define an interface that the proxy will implement.

Create an InvocationHandler implementation with an invoke() method containing the additional logic.

Use Proxy.newProxyInstance() to generate the proxy object, passing the class loader, interface array, and handler.

Invoke methods on the proxy ; the call is delegated to the handler’s invoke(), where you can call the original method via reflection and add pre‑/post‑processing.

JDK dynamic proxy example

Below is a complete example.

public interface UserService {
    void addUser(String name);
}

public class UserServiceImpl implements UserService {
    public void addUser(String name) {
        System.out.println("add user: " + name);
    }
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class UserServiceProxy implements InvocationHandler {
    private Object target;
    public UserServiceProxy(Object target) { this.target = target; }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before method: " + method.getName());
        Object result = method.invoke(target, args);
        System.out.println("after method: " + method.getName());
        return result;
    }
}

import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        UserService proxy = (UserService) Proxy.newProxyInstance(
            userService.getClass().getClassLoader(),
            userService.getClass().getInterfaces(),
            new UserServiceProxy(userService)
        );
        proxy.addUser("Tom");
    }
}

The newProxyInstance method takes three arguments:

ClassLoader to load the generated proxy class.

Array of interfaces that the proxy implements.

InvocationHandler that handles method calls.

Running the program prints:

before method: addUser
add user: Tom
after method: addUser

This demonstrates that the proxy successfully intercepts the addUser call, executing custom logic before and after the original method.

The article concludes with a brief note that the reader can now understand and apply JDK dynamic proxies in their own projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ReflectionInvocationHandler
Architect Chen
Written by

Architect Chen

Sharing over a decade of architecture experience from Baidu, Alibaba, and Tencent.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.