CKTIS / Java
Java dynamic proxies: chaining reflective method calls
Choose a class loader for an interface proxy, identify the intercepted method, and follow its arguments and result through two handlers to the real service.
Version: Java SE 21
Syntax
ClassLoader loader = Service.class.getClassLoader();
InvocationHandler handler = (proxy, method, args) -> {
System.out.println(method.getName());
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
};
Service service = (Service) Proxy.newProxyInstance(
loader, new Class<?>[] { Service.class }, handler);In Java SE 21, Proxy.newProxyInstance from java.lang.reflect takes a class loader, an array of interfaces, and an invocation handler. It returns an instance of a runtime-generated proxy class as Object. Cast the result to a listed interface, not to the concrete service class: the proxy does not subclass that implementation.
Class.getClassLoader returns the loader that loaded the type represented by the Class object. Here, Service.class.getClassLoader() gets the interface's loader. The chosen loader must resolve each proxy interface by name to the very same Class object. Some implementations use null for the bootstrap loader, and a permission check under an installed security manager can cause SecurityException.
InvocationHandler.invoke(proxy, method, args) receives the proxy, the Method describing the call, and its arguments as an Object[]. No parameters means args is null; primitive arguments are boxed. The shorthand Method.invoke/getName refers to two different operations: Method.getName() returns only the name, so both add overloads produce the same text, whereas Method.invoke(target, args) uses the overload identified by method. For instance methods, the call uses dynamic dispatch: the runtime type of target determines which implementation runs. Method.invoke accepts a null argument array for a no-parameter method and boxes primitive results.
The outer handler forwards to the inner proxy, and the inner handler forwards to the implementation. Invoking on the current proxy instead of target would re-enter the same handler. Reflective access can fail with IllegalAccessException. An exception from the invoked method is wrapped in InvocationTargetException, so the example rethrows its cause. If a checked exception escapes the handler and the interface method's throws clause does not permit it, the proxy wraps it in UndeclaredThrowableException.
The program calls only three service methods. Calls to equals, hashCode, and toString on a proxy also reach the handler, with Object as the declaring class; getClass() does not. Do not assume simple forwarding preserves the equals contract. Interface default methods also reach the handler, which can use InvocationHandler.invokeDefault to run an eligible default implementation.
Examples
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
public class ProxyChainDemo {
public interface Service {
String status();
int add(int x);
int add(int x, int y);
}
private static final class RealService implements Service {
@Override
public String status() { return "ready"; }
@Override
public int add(int x) { return x + 1; }
@Override
public int add(int x, int y) { return x + y; }
}
private static Service wrap(String label, Service target) {
InvocationHandler handler = (proxy, method, args) -> {
System.out.println(label + ": " + method.getName());
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
};
return (Service) Proxy.newProxyInstance(
Service.class.getClassLoader(),
new Class<?>[] { Service.class },
handler);
}
public static void main(String[] args) {
Service inner = wrap("inner", new RealService());
Service outer = wrap("outer", inner);
System.out.println(outer.status());
System.out.println(outer.add(4));
System.out.println(outer.add(4, 7));
}
}Result
outer: status inner: status ready outer: add inner: add 5 outer: add inner: add 11
For each call, expect the `outer` log first, then `inner`, then the result. Both overloads log `add`, but return `5` and `11` respectively.
Related lessons
- Java · Lesson 55 · Advanced · Version: 2