Metaprogramming

metaprogramming1DynamicProxy

Path
pkg17metaprogramming/metaprogramming1DynamicProxy.java
Package
pkg17metaprogramming
Study order
1
Run
Single-file source launch
Command
java pkg17metaprogramming/metaprogramming1DynamicProxy.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg17metaprogramming/metaprogramming1DynamicProxy.java
1package pkg17metaprogramming;2 3import java.lang.reflect.InvocationHandler;4import java.lang.reflect.Method;5import java.lang.reflect.Proxy;6 7/*8 * metaprogramming1DynamicProxy.java9 * ---------------------------------10 * Dynamic proxies: create interface implementations at runtime via Proxy.11 *12 * DEFINITION:13 *   java.lang.reflect.Proxy generates a class that implements one or more14 *   interfaces. InvocationHandler receives every method call — basis for15 *   decorators, logging, transaction wrappers, and mock frameworks.16 *17 * KEY POINTS:18 *   - Only interfaces can be proxied (use bytecode libs for classes).19 *   - InvocationHandler.invoke() receives Method, args, and can delegate.20 *   - Used by Spring AOP, Mockito, Hibernate lazy loading.21 */22public class metaprogramming1DynamicProxy {23 24    interface Greeter { String greet(String name); }25 26    public static void main(String[] args) {27        Greeter real = name -> "Hello, " + name;28 29        Greeter logged = (Greeter) Proxy.newProxyInstance(30                Greeter.class.getModule().getClassLoader(),31                new Class<?>[] { Greeter.class },32                new InvocationHandler() {33                    final Greeter target = real;34                    @Override35                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {36                        System.out.println("  -> calling " + method.getName() + "(" + args[0] + ")");37                        Object result = method.invoke(target, args);38                        System.out.println("  <- result: " + result);39                        return result;40                    }41                });42 43        System.out.println(logged.greet("Ada"));44    }45}