利用JAVA反射技术实现动态代理,拦截JAVA方法的执行简单代码示例
时间: 2023-05-18 19:07:38 浏览: 83
以下是一个简单的JAVA反射技术实现动态代理的示例代码:
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class DynamicProxyExample {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
InvocationHandler handler = new ProxySubject(realSubject);
Subject proxySubject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler);
proxySubject.request();
}
}
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() {
System.out.println("RealSubject request");
}
}
class ProxySubject implements InvocationHandler {
private Object target;
public ProxySubject(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoke " + method.getName());
Object result = method.invoke(target, args);
System.out.println("After invoke " + method.getName());
return result;
}
}
```
在这个示例中,我们定义了一个接口 `Subject` 和一个实现类 `RealSubject`,然后我们使用 `ProxySubject` 类来实现动态代理。在 `ProxySubject` 类中,我们使用了 `invoke` 方法来拦截 `RealSubject` 类中的方法执行,并在方法执行前后打印日志。最后,我们使用 `Proxy.newProxyInstance` 方法来创建代理对象,并调用代理对象的 `request` 方法。
注意:这只是一个简单的示例,实际上动态代理的实现要比这个复杂得多。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)