静态代理
定义抽象接口
public interface IRequest{
void request(String params);
}
被代理类1
static class Retrofit implements IRequest{
@Override
public void request(String params) {
System.out.println("Retrofit request" + params);
}
}
被代理类2
static class Volley implements IRequest{
public Volley(){}
@Override
public void request(String params) {
System.out.println("volley request" + params);
}
}
代理类
static class ProxyRequest implements IRequest{
private IRequest request;
public ProxyRequest(IRequest request){
this.request = request;
}
@Override
public void request(String params) {
System.out.println("proxy request");
request.request(params);
}
}
执行
IRequest request = new Volley();
request = new Retrofit();
new ProxyRequest(request).request("ProxyRequest");
运行结果:
proxy request
Retrofit requestProxyRequest
动态代理
static class ProxyHandler implements InvocationHandler{
private Object tar;
public Object bind(Object tar){
this.tar = tar;
return Proxy.newProxyInstance(tar.getClass().getClassLoader(),
tar.getClass().getInterfaces()
, this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
if(method.getName().equals("request")){
System.out.println("执行request前:");
}
result = method.invoke(tar, args);
if(method.getName().equals("request")){
System.out.println("执行request后:");
}
return result;
}
}
执行:
((IRequest)new ProxyHandler().bind(new Volley())).request("ProxyHandler");
结果:
执行request前:
volley requestProxyHandler
执行request后:
动态代理的好处在于,可以对方法执行进行aop切面处理。
动态代理经常可以用于Hook源码使用。