这里主要运用到了注解和反射的知识,下面贴出来关键代码以及注释。
关键代码:
- 创建RequestFactory
static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
return new Builder(retrofit, method).build();
}
- build()方法初始化
RequestFactory build() {
//处理解析方法(GET、POST...)
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
...
//获取参数个数
int parameterCount = parameterAnnotationsArray.length;
//生成参数处理器(根据注解,这一步获取了参数类型)
parameterHandlers = new ParameterHandler<?>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
parameterHandlers[p] = parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p]);
}
...
return new RequestFactory(this);
}
- 调用create方法
okhttp3.Request create(Object[] args) throws IOException {
//获取参数管理器
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
//获取参数的值
int argumentCount = args.length;
...
//生成RequestBuilder
RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl,
headers, contentType, hasBody, isFormEncoded, isMultipart);
//argumentList中添加参数值,规范relativeUrl格式。
List<Object> argumentList = new ArrayList<>(argumentCount);
for (int p = 0; p < argumentCount; p++) {
argumentList.add(args[p]);
handlers[p].apply(requestBuilder, args[p]);
}
//生成网络请求
return requestBuilder.get()
.tag(Invocation.class, new Invocation(method, argumentList))
.build();
}