动态代理实现代码
时间: 2023-10-26 17:16:04 浏览: 68
动态代理是通过在运行时动态生成代理类来实现的。Java 中提供了两种动态代理方式:基于接口的动态代理和基于类的动态代理。
基于接口的动态代理示例代码:
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Hello {
void sayHello();
}
class HelloImpl implements Hello {
public void sayHello() {
System.out.println("Hello World!");
}
}
class DynamicProxyHandler implements InvocationHandler {
private Object obj;
public DynamicProxyHandler(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(obj, args);
return result;
}
}
public class DynamicProxyDemo {
public static void main(String[] args) {
Hello hello = new HelloImpl();
InvocationHandler handler = new DynamicProxyHandler(hello);
Hello proxyHello = (Hello) Proxy.newProxyInstance(hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(), handler);
proxyHello.sayHello();
}
}
```
基于类的动态代理示例代码:
```java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
class Hello {
public void sayHello() {
System.out.println("Hello World!");
}
}
class DynamicProxyHandler implements InvocationHandler {
private Object obj;
public DynamicProxyHandler(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(obj, args);
return result;
}
}
public class DynamicProxyDemo {
public static void main(String[] args) {
Hello hello = new Hello();
InvocationHandler handler = new DynamicProxyHandler(hello);
Hello proxyHello = (Hello) Proxy.newProxyInstance(hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(), handler);
proxyHello.sayHello();
}
}
```
以上两段代码分别实现了基于接口和基于类的动态代理,可以根据需要选择使用。
阅读全文