图文+视频双管齐下,带你全面彻底理解Retrofit源码,学完还不懂请砍我!【墙裂建议收藏(1)

总结

在清楚了各个大厂的面试重点之后,就能很好的提高你刷题以及面试准备的效率,接下来小编也为大家准备了最新的互联网大厂资料。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

static ServiceMethod parseAnnotations(Retrofit retrofit, Method method) {
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);
}
if (returnType == void.class) {
throw methodError(method, “Service methods cannot return void.”);
}

return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}

RequestFactory

首先RequestFactory中的parseAnnotations()最终通过build()方法来构建一个RequestFactory,用来保存解析出来的方法信息。

RequestFactory build() {
//1.解析方法上的注解
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}

int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler<?>[parameterCount];
//2.循环遍历方法中的各个参数,解析参数的注解
for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
parameterHandlers[p] =
parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
}

return new RequestFactory(this);
}

可以看到主要分为两步:

  1. 通过parseMethodAnnotation来解析出请求的方式,例如GETPOSTPUT等等;同时也会验证一些注解的合规使用,例如MultipartFormUrlEncoded只能使用一个。
  2. 通过parseParameter来解析出请求的参数信息,例如PathUrlQuery等等;同时也对它们的合规使用做了验证,例如QueryMapFieldMap等注解它们的key都必须为String类型。这些注解的解析都是在parseParameterAnnotation()方法中进行的。

上面的p == lastParameter需要特别注意下,为何要专门判断该参数是否为最后一个呢?请继续向下看。

协程的判断条件

下面我们来着重看下parseParameter的源码,因为从这里开始就涉及到协程的判断。

private @Nullable ParameterHandler<?> parseParameter( int p, Type parameterType, @Nullable Annotation[] annotations, boolean allowContinuation) { ParameterHandler<?> result = null;
if (annotations != null) {
for (Annotation annotation : annotations) {
//1.解析方法参数的注解,并验证它们的合法性
ParameterHandler<?> annotationAction =
parseParameterAnnotation(p, parameterType, annotations, annotation);

if (annotationAction == null) {
continue;
}

//每个参数都只能有一个注解
if (result != null) {
throw parameterError(method, p,
“Multiple Retrofit annotations found, only one allowed.”);
}

result = annotationAction;
}
}

//2.判断是否是协程
if (result == null) {
if (allowContinuation) {
try {
if (Utils.getRawType(parameterType) == Continuation.class) {
isKotlinSuspendFunction = true;
return null;
}
} catch (NoClassDefFoundError ignored) {
}
}
throw parameterError(method, p, “No Retrofit annotation found.”);
}

return result;
}

第一点没什么好说的,里面没什么逻辑,就是一个纯注解解析与Converter的选取。

第二点是关键点,用来判断该方法的调用是否使用到了协程。同时有个allowContinuation参数,这个是什么呢?我们向上看,发现它是方法中的一个参数,如果我们继续追溯就会发现它就是我们之前特意需要注意的p == lastParameter

所以判断是否是使用了协程有三步:

  1. result为空,即该参数没有注解
  2. allowContinuationtrue,即是最后一个参数
  3. Continuation.class,说明该参数的类型为Continuation

只有符合上述三点才能证明使用了协程,但脑海里回想一下协程的写法,发现完全对不到这三点…

到这里可能有的读者已经开始蒙圈了,如果你没有深入了解协程的话,这个是正常的状态。

别急,要理解这块,还需要一点协程的原理知识,下面我来简单说一下协程的部分实现原理。

suspend原理

我们先来看下使用协程是怎么写的:

@GET(“/v2/news”)
suspend fun newsGet(@QueryMap params: Map<String, String>): NewsResponse

这是一个标准的协程写法,然后我们再套用上面的条件,发现完全匹配不到。

因为,这是不协程的本来面目。我们思考一个问题,为什么使用协程要添加suspend关键字呢?这是重点。你可以多想几分钟。

(几分钟之后…)

不吊大家胃口了,我这里就直接说结论。

因为在代码编译的过程中会自动为带有suspend的函数添加一个Continuation类型的参数,并将其添加到最后面。所以上面的协程真正的面目是这样的:

@GET(“/v2/news”)
fun newsGet(@QueryMap params: Map<String, String>, c: Continuation): NewsResponse

现在我们再来看上面的条件,发现能够全部符合了。

由于篇幅有限,有关协程的原理实现就点到为止,后续我会专门写一个协程系列,希望到时能够让读者们认识到协程的真面目,大家可以期待一下。

现在我们已经知道了Retrofit如何判断一个方法是否使用了协程。那么我们再进入另一个点:

Retrofit如何将Call直接转化为NewResonse,简单的说就是支持使newsGet方法返回NewsResponse。而这一步的转化在HttpServiceMethod中。

HttpServiceMethod

上面已经分析完RequestFactoryparseAnnotations(),现在再来看下HttpServiceMethod中的parseAnnotations()

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;
// 1. 是协程
if (isKotlinSuspendFunction) {
Type[] parameterTypes = method.getGenericParameterTypes();
Type responseType = Utils.getParameterLowerBound(0,
(ParameterizedType) parameterTypes[parameterTypes.length - 1]);
// 2. 判断接口方法返回的类型是否是Response
if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
// Unwrap the actual body type from Response.
responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
continuationWantsResponse = true;
} else {
// TODO figure out if type is nullable or not
// Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
// Find the entry for method
// Determine if return type is nullable or not
}

// 3. 注意:将方法返回类型伪装成Call类型,并将SkipCallbackExecutor注解添加到annotations中
adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
} else {
adapterType = method.getGenericReturnType();
}

// 4. 创建CallAdapter,适配call,将其转化成需要的类型
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
// 5. 创建Converter,将响应的数据转化成对应的model类型
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);

okhttp3.Call.Factory callFactory = retrofit.callFactory;
// 6. 接口方法不是协程
if (!isKotlinSuspendFunction) {
return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
// 7. 接口方法是协程,同时返回类型是Response类型
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call>) callAdapter);
} else {
// 8. 接口方法是协程,同时返回类型是body,即自定义的model类型
//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,
callFactory, responseConverter, (CallAdapter<ResponseT, Call>) callAdapter,
continuationBodyNullable);
}
}

代码中已经解析的很清楚了,需要注意3,如果是协程会做两步操作,首先将接口方法的返回类型伪装成Call类型,然后再将SkipCallbackExecutor手动添加到annotations中。字面意思就在后续调用callAdapter.adapt(call)时,跳过创建Executor,简单理解就是协程不需要Executor来切换线程的。为什么这样?这一点先放这里,后续创建Call的时候再说。

我们直接看协程的7,8部分。7也不详细分析,简单提一下,它就是返回一个Response<T>的类型,这个Retrofit最基本的支持了。至于如何在使用协程时将Call<T>转化成Response<T>原理与8基本相同,只是比8少一步,将它的body转化成对应的返回类型model。所以下面我们直接看8。

将Call转化成对应的Model

static final class SuspendForBody extends HttpServiceMethod<ResponseT, Object> {
private final CallAdapter<ResponseT, Call> callAdapter;
private final boolean isNullable;

SuspendForBody(RequestFactory requestFactory, okhttp3.Call.Factory callFactory,
Converter<ResponseBody, ResponseT> responseConverter,
CallAdapter<ResponseT, Call> callAdapter, boolean isNullable) {
super(requestFactory, callFactory, responseConverter);
this.callAdapter = callAdapter;
this.isNullable = isNullable;
}

@Override protected Object adapt(Call call, Object[] args) {
// 1. 获取适配的Call
call = callAdapter.adapt(call);

//noinspection unchecked Checked by reflection inside RequestFactory.
// 2. 获取协程的Continuation
Continuation continuation = (Continuation) args[args.length - 1];
return isNullable
? KotlinExtensions.awaitNullable(call, continuation)
: KotlinExtensions.await(call, continuation);
}
}

最后总结我的面试经验

2021年的金三银四一眨眼就到了,对于很多人来说是跳槽的好机会,大厂面试远没有我们想的那么困难,摆好心态,做好准备,你也可以的。

另外,面试中遇到不会的问题不妨尝试讲讲自己的思路,因为有些问题不是考察我们的编程能力,而是逻辑思维表达能力;最后平时要进行自我分析与评价,做好职业规划,不断摸索,提高自己的编程能力和抽象思维能力。

BAT面试经验

实战系列:Spring全家桶+Redis等

其他相关的电子书:源码+调优

面试真题:

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

15512140482)]

[外链图片转存中…(img-iPbKRf6b-1715512140482)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

需要这份系统化的资料的朋友,可以点击这里获取

  • 19
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值