java中返回值类型为t_Retrofit 是如何获取返回值 Call 中的类型 T, 以提供给 Gson 使用的?...

Call的类型 T 即Response的类型 T,获得了Call就能够正确输出给Response。那么Retrofit是怎么做到的呢?

以下是HttpServiceMethod中的 static 方法:

static HttpServiceMethod parseAnnotations(

Retrofit retrofit, Method method, RequestFactory requestFactory) {

// 省略部分代码

// ...

Type adapterType;

// 解析 kotlin 语言中的返回值

if (isKotlinSuspendFunction) {

Type[] parameterTypes = method.getGenericParameterTypes();

Type responseType = Utils.getParameterLowerBound(0,

(ParameterizedType) parameterTypes[parameterTypes.length - 1]);

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

}

adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);

annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);

} else {

// 解析 java 语言写的返回值(写过的都知道,这个很容易懂了)

adapterType = method.getGenericReturnType();

}

// 省略部分代码

// ...

}

拿到adapterType之后,又辗转调用了CallAdapter.Factory. get()以创建实现了CallAdapter接口的CallAdapter:

public interface CallAdapter {

// 省略部分代码

// ...

abstract class Factory {

public abstract @Nullable CallAdapter, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit);

// ...

}

}

注意前面的adapterType是Call,所以要取出里面的T,才是真正要传给 Gson 从而输出的类型:

// 这是 CallAdapter.Factory. get() 的 impl

@Override public @Nullable CallAdapter, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {

if (getRawType(returnType) != Call.class) {

return null;

}

if (!(returnType instanceof ParameterizedType)) {

throw new IllegalArgumentException("Call return type must be parameterized as Call or Call extends Foo>");

}

final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);

// ...

// 在这里 CallAdapter 接口的实现

return new CallAdapter>() {

@Override public Type responseType() {

return responseType;

}

// ...

};

}

Call有类似 GsonTypeToken的功能,如:

@KeepV

data class Data(val users: List)

data class User(val id: Long)

interface AaaService {

@GET("a/b/c.json")

fun getAbc(): Call>

}

能够正确解析出Data,相当于new TypeToken>{}.getType(),所以能传给 Gson 从而 输入正确的Response>。细节就不多讲了,这里主要是做个笔记备忘。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值