java反射之-InvocationHandler使用

发布时间 2023-06-26 09:59:52作者: bean-sprout

InvocationHandler 是 Java 中的一个接口,是 Java 反射 API 的一部分。与 Proxy 类一起使用,用于动态创建接口的代理实例。

在 Java 中使用 Proxy 类创建代理对象时,需要提供一个 InvocationHandler 实现来定义代理对象的行为。InvocationHandler 接口只有一个方法,即 invoke() 方法,它负责处理对代理对象的方法调用。

下面是 InvocationHandler 的使用示例:

 1 import java.lang.reflect.InvocationHandler;
 2 import java.lang.reflect.Method;
 3 import java.lang.reflect.Proxy;
 4 
 5 public class MyInvocationHandler implements InvocationHandler {
 6     private Object target;
 7 
 8     public MyInvocationHandler(Object target) {
 9         this.target = target;
10     }
11 
12     @Override
13     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
14         // 在方法调用之前执行一些操作
15         System.out.println("方法调用前");
16 
17         // 调用目标对象上的方法
18         Object result = method.invoke(target, args);
19 
20         // 在方法调用之后执行一些操作
21         System.out.println("方法调用后");
22 
23         return result;
24     }
25 
26     public static void main(String[] args) {
27         // 创建目标对象
28         MyInterface targetObject = new MyInterfaceImpl();
29 
30         // 创建代理对象
31         MyInterface proxyObject = (MyInterface) Proxy.newProxyInstance(
32                 MyInterface.class.getClassLoader(),
33                 new Class<?>[]{MyInterface.class},
34                 new MyInvocationHandler(targetObject)
35         );
36 
37         // 在代理对象上调用方法
38         proxyObject.someMethod();
39     }
40 }
41 
42 interface MyInterface {
43     void someMethod();
44 }
45 
46 class MyInterfaceImpl implements MyInterface {
47     @Override
48     public void someMethod() {
49         System.out.println("执行 someMethod");
50     }
51 }

 

在这个示例中,MyInvocationHandler 类实现了 InvocationHandler 接口。它在构造函数中接收一个目标对象 (MyInterfaceImpl),在 invoke() 方法中,在调用目标对象上的方法之前和之后执行一些操作。

main() 方法中,使用 Proxy.newProxyInstance() 方法创建了一个代理对象,传递了 MyInterface 类加载器、接口数组(在此例中是 MyInterface),以及 MyInvocationHandler 的实例。当在代理对象上调用 someMethod() 方法时,将调用 MyInvocationHandlerinvoke() 方法,允许你拦截并在目标对象上的方法执行之前和之后执行其他操作。

--来自chatgpt