java 拦截所有方法
时间: 2023-08-04 11:15:55 浏览: 62
在 Java 中,我们可以使用 `InvocationHandler` 接口和动态代理来拦截所有方法。具体来说,我们可以实现一个通用的 `InvocationHandler` 类,其中的 `invoke` 方法可以拦截任何方法的调用,并执行拦截逻辑。
下面是一个示例代码,演示如何拦截所有方法:
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MethodInterceptor implements InvocationHandler {
private Object target;
public MethodInterceptor(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method invocation: " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After method invocation: " + method.getName());
return result;
}
public static Object createProxy(Object target) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new MethodInterceptor(target));
}
}
```
在上面的示例代码中,我们定义了一个 `MethodInterceptor` 类,实现了 `InvocationHandler` 接口,并在 `invoke` 方法中实现了方法拦截的逻辑。具体来说,我们在方法执行前后打印了方法名。
为了使用这个拦截器,我们还实现了一个 `createProxy` 方法,用于创建代理对象。该方法使用 `Proxy.newProxyInstance` 方法来创建代理对象,并将 `MethodInterceptor` 对象作为拦截器传递给代理对象。
使用时,我们只需要将需要拦截的对象作为参数传递给 `createProxy` 方法即可。例如:
```java
public class Demo {
public static void main(String[] args) {
MyInterface obj = new MyImpl();
MyInterface proxy = (MyInterface) MethodInterceptor.createProxy(obj);
proxy.method1();
proxy.method2();
}
}
interface MyInterface {
void method1();
void method2();
}
class MyImpl implements MyInterface {
public void method1() {
System.out.println("MyImpl method1");
}
public void method2() {
System.out.println("MyImpl method2");
}
}
```
在上面的示例代码中,我们定义了一个 `MyInterface` 接口和一个实现类 `MyImpl`,并在 `Demo` 类中使用 `MethodInterceptor` 来拦截 `MyImpl` 对象的所有方法。当我们运行这段代码时,输出结果如下:
```
Before method invocation: method1
MyImpl method1
After method invocation: method1
Before method invocation: method2
MyImpl method2
After method invocation: method2
```
可以看到,我们成功地拦截了 `MyImpl` 对象的所有方法,并在方法执行前后打印了方法名。由此可见,使用 `InvocationHandler` 接口和动态代理,我们可以轻松地实现方法拦截和增强。