你可以写一个JDK代理的代码吗
时间: 2023-03-27 09:01:36 浏览: 93
可以,以下是一个简单的 JDK 代理的代码示例:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyExample {
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();
}
static class RealSubject implements Subject {
@Override
public void request() {
System.out.println("RealSubject request");
}
}
static class ProxySubject implements InvocationHandler {
private Object target;
public ProxySubject(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before request");
Object result = method.invoke(target, args);
System.out.println("after request");
return result;
}
}
}
阅读全文