1. 定义接口
2.实现接口的具体类
3.创建 InvocationHandler 实现
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method execution"); Object result = method.invoke(target, args); // 调用实际方法 System.out.println("After method execution"); return result; } }
4. 使用 Proxy
类来创建代理对象
Proxy.newProxyInstance( target.getClass().getClassLoader(), // 类加载器 target.getClass().getInterfaces(), // 被代理对象的接口 handler);
标签:target,jdk,Object,代理,public,InvocationHandler,动态,method From: https://www.cnblogs.com/towboa/p/18442805