代理机制:
1. 创建代理对象, Proxy.newProxyInstance
时,JVM 会:
- 生成代理类的字节码:使用字节码技术生成一个代理类,该代理类实现了所提供的接口。这种代理类继承自
java.lang.reflect.Proxy
并实现了指定的接口。 - 动态加载代理类:将生成的代理类加载到 JVM 中
2. 代理类方法调用
代理类的每个接口方法都会被重写。在重写的方法中,JVM 会自动将调用转发到 InvocationHandler.invoke
方法。具体步骤如下:
先定义好interface 和 对应实现类impl(以下省略,interface service, 有一个方法perform() )
1. 使用 Proxy.newProxyInstance
创建代理对象,将自定义的 InvocationHandler
传入
import java.lang.reflect.Proxy; public class Main { public static void main(String[] args) { // 被代理的原始对象 Service service = new ServiceImpl(); // 创建代理对象 Service proxyInstance = (Service) Proxy.newProxyInstance( service.getClass().getClassLoader(), // 类加载器 service.getClass().getInterfaces(), // 目标对象实现的接口 new ServiceInvocationHandler(service) // InvocationHandler 实现 ); // 调用代理对象的方法 proxyInstance.performTask(); } }
2.InvocationHandler
实现
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ServiceInvocationHandler implements InvocationHandler { private final Object target; // 构造方法接收被代理的对象 public ServiceInvocationHandler(Object target) { this.target = target; } // 实现 invoke 方法,添加日志逻辑 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method: " + method.getName()); Object result = method.invoke(target, args); // 调用目标对象的方法 System.out.println("After method: " + method.getName()); return result; } }