常常利用动态代理来实现拦截器,retrofit的原理可以这样简单描述为:利用动态代理拦截到方法、参数,再根据我们在方法上的注解,去拼接为一个正常的Okhttp请求,然后执行。
简单例子:
public interface IUserService {
void login(String username, String password);
}
IUserService userService = (IUserService) Proxy.newProxyInstance(IUserService.class.getClassLoader(),
new Class[]{IUserService.class},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Log.e("wy", "method = " + method.getName() +
" , args = " + Arrays.toString(args) +" proxy:"+proxy.toString());
return null;
}
});
Log.e("wy", "userService.getClass(): "+userService.getClass() );
userService.login("wy","123");
执行日志
2022-09-06 09:51:40.403 12141-12141/com.example.myapplication E/wy: userService.getClass(): class $Proxy1
2022-09-06 09:51:40.403 12141-12141/com.example.myapplication E/wy: method = login , args = [wy, 123]
仅仅是一个接口,就能产生一个该接口的对象,然后我们还能拦截它的方法