Use Java dynamic proxies when cross-cutting behavior should wrap many interface implementations without hand-writing one proxy class per type.
Java dynamic proxies let you create proxy behavior at runtime for interface-based types.
Dynamic proxies are useful when the access concern is the same across many targets:
Instead of writing one proxy class per interface, Java routes calls through an InvocationHandler.
1InvocationHandler handler = (proxy, method, args) -> {
2 long start = System.nanoTime();
3 try {
4 return method.invoke(target, args);
5 } finally {
6 System.out.println(method.getName() + " took " + (System.nanoTime() - start));
7 }
8};
Dynamic proxies work naturally for interfaces. They are not a universal replacement for explicit proxy classes. If the access rule is domain-specific and important to read directly, a named hand-written proxy may still be clearer.
Use dynamic proxies for reusable cross-cutting access behavior, not for hiding core domain design.