Java Reference ยท Language Features by Version
Dynamic proxies (java.lang.reflect.Proxy)
Reference for java.lang.reflect.Proxy and InvocationHandler: create objects that implement interfaces at run time for logging, caching, transactions and mocking.
A dynamic proxy is an object created at run time that implements one or more interfaces you choose. Every method call on the proxy is forwarded to a single InvocationHandler, which receives the proxy, the Method that was called and the arguments, and decides what to do: call a real object, add logging, check permissions, cache a result, return a canned value, or all of these.
This is how many frameworks add behavior without you writing a wrapper class per interface: transactions around a service, retry logic, remote calls that look like local ones, and mock objects in tests. Dynamic proxies work only for interfaces. To proxy a class you need a bytecode library or a different approach.
Greeter proxy = (Greeter) Proxy.newProxyInstance( Greeter.class.getClassLoader(), new Class<?>[] { Greeter.class }, (proxyObject, method, args) -> method.invoke(real, args));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) @FunctionalInterface public interface InvocationHandler { Object invoke(Object proxy, Method method, Object[] args) throws Throwable; }
| Name | Description |
|---|---|
loader |
Class loader that defines the proxy class; normally the interface's loader. All interfaces must be visible from it. |
interfaces |
Interfaces the proxy implements. They must be interfaces, with no duplicates. |
h |
Receives every call. |
proxy (in invoke) |
The proxy object itself. Do not call methods on it from the handler unless you intend recursion. |
method |
The interface method that was called (for toString, equals and hashCode, the Object method). |
args |
Arguments, or null for methods with no parameters. Primitives are boxed. |
Returns: a new object implementing all the interfaces. Throws: IllegalArgumentException if the interfaces are invalid (a class, a duplicate, or not visible from the loader) and NullPointerException for null arguments.
Other useful statics: Proxy.isProxyClass(Class), Proxy.getInvocationHandler(Object), and InvocationHandler.invokeDefault(proxy, method, args) (Java 16) to call an interface's default method from the handler.
Usage notes
- What the handler returns must fit the method's return type. Returning
nullfor a primitive return type throwsNullPointerException; a wrong type throwsClassCastException. - Exceptions: a checked exception thrown by the handler that the interface method does not declare is wrapped in
UndeclaredThrowableException. UnwrapInvocationTargetExceptionbefore rethrowing, as the first example does. toString,hashCodeandequalsof the proxy are also sent to the handler. Handle them, or you will get surprises in logs and collections.- Default methods are intercepted like abstract ones. Use
InvocationHandler.invokeDefaultto run the interface's own implementation. - Never print
proxy.getClass().getName()and expect a stable name; it looks likejdk.proxy1.$Proxy0and depends on the loading order. - Cost: each call goes through reflection (
Method.invoke). It is acceptable for service-level calls, not for inner loops. - Proxying classes is not possible with
java.lang.reflect.Proxy; frameworks use libraries that generate subclasses for that. Final classes and methods cannot be proxied that way either. - Proxies of the same interfaces and loader share one generated class, so the cost of creating a second one is small.