用java写一个动态代理
时间: 2024-03-09 15:19:20 浏览: 22
动态代理是指在运行时动态生成代理类,而不需要事先编写代理类的代码。Java中的动态代理主要是通过Java.lang.reflect.Proxy类实现的。
下面是一个简单的动态代理示例,用于打印方法调用前后的时间戳:
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
public class DynamicProxyDemo {
public static void main(String[] args) {
// 创建被代理对象
HelloServiceImpl helloService = new HelloServiceImpl();
// 创建代理对象
HelloService proxy = (HelloService) Proxy.newProxyInstance(
helloService.getClass().getClassLoader(),
helloService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 打印时间戳
System.out.println(new Date() + " " + method.getName() + "() start");
// 调用被代理对象的方法
Object result = method.invoke(helloService, args);
// 打印时间戳
System.out.println(new Date() + " " + method.getName() + "() end");
return result;
}
});
// 调用代理对象的方法
proxy.sayHello("World");
}
}
interface HelloService {
void sayHello(String name);
}
class HelloServiceImpl implements HelloService {
@Override
public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
```
在上面的示例中,我们创建了一个HelloServiceImpl的实例作为被代理对象,然后通过Proxy.newProxyInstance方法创建了一个代理对象,同时指定了代理对象的处理器InvocationHandler。在InvocationHandler中,我们实现了代理对象方法的调用,包括方法调用前后的时间戳打印。最后,我们通过代理对象调用了HelloService接口中的sayHello方法,实际上调用的是被代理对象HelloServiceImpl中的sayHello方法,同时在方法调用前后打印了时间戳。
运行上面的代码,输出如下:
```
Wed Jun 30 19:07:37 CST 2021 sayHello() start
Hello, World!
Wed Jun 30 19:07:37 CST 2021 sayHello() end
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)