-
ServiceMethod
可以理解為 Java Interface API
的靜態(tài)映射;
- 生成
ServiceMethod
abstract class ServiceMethod<T> {
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
//解析 Annotation 漏健,生成RequestFactory
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
//返回類型不支持泛型或者通配符類型
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(method,
"Method return type must not include a type variable or wildcard: %s", returnType);
}
//返回類型不支持 void 類型
if (returnType == void.class) {
throw methodError(method, "Service methods cannot return void.");
}
//生成 ServiceMethod
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
abstract @Nullable T invoke(Object[] args);
}
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
//通過 Method 生成 RequestFactory嚎货,RequestFactory#create 可以生成最終發(fā)起請求的 Request
return new Builder(retrofit, method).build();
}
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
boolean continuationWantsResponse = false;
boolean continuationBodyNullable = false;
Annotation[] annotations = method.getAnnotations();
Type adapterType;
if (isKotlinSuspendFunction) {
//kotlin 掛起函數(shù) 相關邏輯
} else {
// Method 返回類型(包括類型引元)
adapterType = method.getGenericReturnType();
}
//根據(jù) adapterType 找到匹配的 CallAdapter
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
//返回 CallAdapter 指定的 responseType
Type responseType = callAdapter.responseType();
//根據(jù) responseType 找到匹配的Converter
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
//生成ServiceMethod
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
continuationBodyNullable);
}
}
-
RequestFactory#parseAnnotations
通過 Method
生成 RequestFactory
; RequestFactory#create
生成最終發(fā)起請求的 Request
蔫浆;
-
RequestFactory.Builder
中關于各種注解的解析殖属,可自行查看源碼;
-
ServiceMethod#parseAnnotations
- 先通過
Method
的返回類型(包括類型引元)找到匹配的 CallAdapter
瓦盛;
- 再通過
CallAdapter#responseAdapter
找到匹配的響應數(shù)據(jù)的 Converter
洗显;
- 通過
RequestFactory
Call.Factory
Converter
CallAdapter
生成 CallAdapted
,CallAdapted
是 ServiceMethod
的子類原环;
-
ServiceMethod
的調(diào)用
ReturnT invoke(Object[] args) {
Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
return adapt(call, args);
}
@Override protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
return callAdapter.adapt(call);
}
-
Java Interface API
的調(diào)用就是 ServiceMethod
的調(diào)用挠唆,即調(diào)用 ServiceMethod#invoke
;
- 根據(jù)
RequestFactory
Call.Factory
Converter
生成 OkHttpCall
嘱吗,內(nèi)部持有 Okhttp
的 Call
损搬,所以 Retrofit
的網(wǎng)絡請求是由 OkHttp
處理的,并且無法更改柜与;
- 根據(jù)
CallAdapter
返回 Java Interface API
的返回類型的對象巧勤,并把 OkHttpCall
通過參數(shù)傳遞給 CallAdapter
;
-
Retrofit/Builder
-
Retrofit
對象是通過 Retrofit.Builder
生成的弄匕,有各種配置項颅悉;
//緩存接口方法對應的 ServiceMethod
private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
//通過 Factory 生成的 Call 對象發(fā)起網(wǎng)絡請求
final okhttp3.Call.Factory callFactory;
//用于拼接url
final HttpUrl baseUrl;
//請求數(shù)據(jù)/響應數(shù)據(jù)
final List<Converter.Factory> converterFactories;
// HTTP Call 對象轉化器
final List<CallAdapter.Factory> callAdapterFactories;
//異步回調(diào)分發(fā)器
final @Nullable Executor callbackExecutor;
//ServiceMethod預加載
final boolean validateEagerly;
-
serviceMethodCache
用于緩存 Java Interface API
對應的 ServiceMethod
;
-
callFactory
用于生成真正發(fā)情網(wǎng)絡請求的 HTTP Call
迁匠;默認會創(chuàng)建一個 OkHttpClient
剩瓶;
-
converterFactories
用于生成 請求數(shù)據(jù)/響應數(shù)據(jù) 轉化器;要注意添加 Converter.Factory
的順序城丧;
-
callAdapterFactories
用于生成 HTTP Call
適配器延曙,將 Retrofit
內(nèi)置的 HTTP Call
轉化為 Java Interface API
返回的 HTTP Call
;要注意添加 CallAdapter
的順序亡哄;
-
callbackExecutor
表示異步回調(diào)分發(fā)器枝缔;默認是主線程;
-
validateEagerly
表示是否預加載 ServiceMethod
;如果為 true
愿卸,則在創(chuàng)建 Java Interfae
對應的動態(tài)代理對象時灵临,預加載該 Java Interface
所有 API 對應的 ServiceMethod
;
-
Retrofit#create
public <T> T create(final Class<T> service) {
// Java Interface 校驗趴荸,ServiceMethod 預加載
validateServiceInterface(service);
//生成動態(tài)代理對象
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
private final Object[] emptyArgs = new Object[0];
@Override public @Nullable Object invoke(Object proxy, Method method,
@Nullable Object[] args) throws Throwable {
// 如果是 Object 的 API 調(diào)用儒溉,直接調(diào)用
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
// 如果是 Java Interface 中的默認方法調(diào)用
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
// 通過 ServiceMethod 代理調(diào)用
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
private void validateServiceInterface(Class<?> service) {
// 指定的類必須為 Interface
if (!service.isInterface()) {
throw new IllegalArgumentException("API declarations must be interfaces.");
}
Deque<Class<?>> check = new ArrayDeque<>(1);
check.add(service);
while (!check.isEmpty()) {
Class<?> candidate = check.removeFirst();
if (candidate.getTypeParameters().length != 0) {
//不支持參數(shù)化類型
StringBuilder message = new StringBuilder("Type parameters are unsupported on ")
.append(candidate.getName());
if (candidate != service) {
message.append(" which is an interface of ")
.append(service.getName());
}
throw new IllegalArgumentException(message.toString());
}
Collections.addAll(check, candidate.getInterfaces());
}
// ServiceMethod 預加載
if (validateEagerly) {
Platform platform = Platform.get();
for (Method method : service.getDeclaredMethods()) {
if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
//加載 ServiceMethod
loadServiceMethod(method);
}
}
}
}
ServiceMethod<?> loadServiceMethod(Method method) {
//如果有緩存,直接返回
ServiceMethod<?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//通過 Method 及相關注解发钝,生成 ServiceMethod 對象顿涣,并緩存
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
- 先校驗指定的
Class
,必須為 Java Interface
酝豪,并且不是參數(shù)化類型园骆;如果要預加載 ServiceMethod
,則通過 Method
及相關的 Annotation
生成 ServiceMethod
并緩存寓调;
- 通過動態(tài)代理為指定的
Java Interface
生成動態(tài)代理對象锌唾,動態(tài)代理可以查看 Java-反射-動態(tài)代理 ;
- 動態(tài)代理對象的方法調(diào)用都會轉發(fā)給綁定的
InvocationHandler#invoke
方法夺英;具體調(diào)用流程后面會有詳細介紹晌涕;
-
Retrofit#callAdapter
//返回匹配 Java Interface API 返回類型的 CallAdapter
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
//返回匹配 Java Interface API 返回類型的 CallAdapter
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
Objects.requireNonNull(returnType, "returnType == null");
Objects.requireNonNull(annotations, "annotations == null");
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
//CallAdapter.Factory 返回不為null,則匹配成功
return adapter;
}
}
}
- 從
callAdapterFactories
中遍歷尋找能匹配 returnType
的CallAdapter痛悯;
-
Retrofit#requestBodyConverter
// 返回 requestBody 的轉化器
public <T> Converter<T, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations) {
return nextRequestBodyConverter(null, type, parameterAnnotations, methodAnnotations);
}
// 返回 requestBody 的轉化器
public <T> Converter<T, RequestBody> nextRequestBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] parameterAnnotations,
Annotation[] methodAnnotations) {
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter.Factory factory = converterFactories.get(i);
Converter<?, RequestBody> converter =
factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, this);
if (converter != null) {
//如果返回的 Converter 不為null余黎,則匹配成功
return (Converter<T, RequestBody>) converter;
}
}
}
- 返回轉化 requestBody 的
Converter
;
- 用于轉化用
Body
Part
PartMap
注解的方法參數(shù)载萌;
-
Retrofit#responseBodyConverter
//返回
public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
return nextResponseBodyConverter(null, type, annotations);
}
public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
@Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
int start = converterFactories.indexOf(skipPast) + 1;
for (int i = start, count = converterFactories.size(); i < count; i++) {
Converter<ResponseBody, ?> converter =
converterFactories.get(i).responseBodyConverter(type, annotations, this);
if (converter != null) {
//如果返回 Converter 不為null惧财,則匹配成功
return (Converter<ResponseBody, T>) converter;
}
}
}
- 返回轉化 responseBody 的
Converter
;
-
Retrofit#stringConverter
//返回 `Conterver` 扭仁,用于將 `Type` 轉化為 `String` 垮衷;
public <T> Converter<T, String> stringConverter(Type type, Annotation[] annotations) {
for (int i = 0, count = converterFactories.size(); i < count; i++) {
Converter<?, String> converter =
converterFactories.get(i).stringConverter(type, annotations, this);
if (converter != null) {
//noinspection unchecked
return (Converter<T, String>) converter;
}
}
//如果沒有匹配到,則返回內(nèi)置的 Converter
return (Converter<T, String>) BuiltInConverters.ToStringConverter.INSTANCE;
}
- 返回
Converter
乖坠,用于將 Type
轉化為 String
搀突;
- 用于轉化用
Field
FieldMap
Header
HeaderMap
Path
Query
QueryMap
注解的方法參數(shù);