温馨提示×

Java中invocationhandler怎么使用

小亿
91
2024-05-29 09:18:57
栏目: 编程语言

在Java中,InvocationHandler接口通常用于动态代理。通过实现InvocationHandler接口,可以在运行时处理代理对象的方法调用。下面是一个简单的示例,演示了如何使用InvocationHandler来创建动态代理:

```java

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;

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 calling " + method.getName());

Object result = method.invoke(target, args);

System.out.println("After calling " + method.getName());

return result;

}

public static void main(String[] args) {

// 创建目标对象

MyClass target = new MyClass();

// 创建InvocationHandler

MyInvocationHandler handler = new MyInvocationHandler(target);

// 创建动态代理对象

MyClassInterface proxy = (MyClassInterface) Proxy.newProxyInstance(

target.getClass().getClassLoader(),

target.getClass().getInterfaces(),

handler);

// 调用代理对象的方法

proxy.doSomething();

}

}

interface MyClassInterface {

void doSomething();

}

class MyClass implements MyClassInterface {

@Override

public void doSomething() {

System.out.println("Doing something");

}

}

```

在上面的示例中,我们首先定义了一个实现了InvocationHandler接口的自定义类MyInvocationHandler。在invoke方法中,我们可以编写在方法调用之前和之后需要执行的逻辑。然后我们在main方法中创建了一个目标对象MyClass和一个对应的InvocationHandler对象,最后使用Proxy.newProxyInstance方法创建了一个动态代理对象proxy。当调用代理对象的方法时,会自动触发MyInvocationHandler中的invoke方法。

0