retrofit 初始化:
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service); //1
if (validateEagerly) {
eagerlyValidateMethods(service);//2
}
//3
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.adapt(okHttpCall);
}
});
}
复制代码
(按照代码中的标签来解释每行代码的作用)
- 检查是否为合法接口(未继承其他接口)。
- 直接生成ServiceMethod。
- 动态代理。接口中方法的具体实现委托给
ServiceMethod
类,retrofit 的主要作用也是通过更简洁的代码来构造HTTP
请求。
java.lang.reflect.Proxy:该类用于动态生成代理类,只需传入目标接口、目标接口的类加载器以及InvocationHandler便可为目标接口生成代理类及代理对象。