美文网首页
Retrofit源码分析(二)

Retrofit源码分析(二)

作者: 深爱蒲公英的纯美 | 来源:发表于2018-08-03 11:11 被阅读0次

上一篇分析了Retrofit的创建过程,也就是如下这段代码的内部实现:

Retrofit retrofit = new Retrofit.Builder()
 *     .baseUrl("https://api.example.com/")
 *     .addConverterFactory(GsonConverterFactory.create())
 *     .build();

这一篇分析创建接口对象的内部实现,也就是下面这段代码:

MyApi api = retrofit.create(MyApi.class);

就这一小行代码,首先我们看看create()方法干了什么,前方高能,我要贴代码了:

public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    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);
            }
            return loadServiceMethod(method).invoke(args);
          }
        });
  }

这个方法的前四行不需要解释了,就是校验接口和方法的合法性。` Proxy.newProxyInstance()这个方法返回了一个此接口的动态代理对象,也就是上面我们看到的api这个对象。
动态代理对象创建好了,我们进行第三步:

 * Response<User> user = api.getUser().execute();

我们以后调用这个动态对象的所有方法的时候都会先走invoke()方法。这个方法中两个if判断,第一个是判断方法是否是object的方法,第二个是判断方法是否是java 8的default方法。重点是loadServiceMethod(method).invoke(args)这一句,车既然开到这了,那么继续往前开吧:

ServiceMethod<?> loadServiceMethod(Method method) {
    ServiceMethod<?> result = serviceMethodCache.get(method);
    if (result != null) return result;

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = ServiceMethod.parseAnnotations(this, method);
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

这个方法中首先是通过method从缓存map中取出ServiceMethod,如果没有,那么就通过ServiceMethod.parseAnnotations(this, method)ServiceMethod的静态方法获取,你也许看到这一懵逼,说怎么不解释一下,对不起,我也不知道它是干啥的目前为止,从方法名字看说是解析注解,想知道干啥的,那我们一起继续往下看:

abstract class ServiceMethod<T> {
  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method 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 new HttpServiceMethod.Builder<Object, T>(retrofit, method).build();
  }

  abstract T invoke(@Nullable Object[] args);
}

好,到了ServiceMethod这个类了,一看,傻眼了,几乎啥也没干呀这,校验了方法返回类型,抛了两个异常之后,就又甩锅了,甩给HttpServiceMethod,这个类一看就是ServiceMethod的实现类,并且又是builder模式,这个类的注释如下:

Adapts an invocation of an interface method into an HTTP call. 
大概的意思是将一个接口的方法调用转化成一个HTTP call

好,那我们就继续看这个类:

  Builder(Retrofit retrofit, Method method) {
      this.retrofit = retrofit;
      this.method = method;
    }

这事HttpServiceMethod.Builder这个类的构造方法,保存了两个变量,没干别的,继续看build()方法:

 HttpServiceMethod<ResponseT, ReturnT> build() {
      requestFactory = RequestFactory.parseAnnotations(retrofit, method);

      callAdapter = createCallAdapter();
      responseType = callAdapter.responseType();
      if (responseType == Response.class || responseType == okhttp3.Response.class) {
        throw methodError(method, "'"
            + Utils.getRawType(responseType).getName()
            + "' is not a valid response body type. Did you mean ResponseBody?");
      }
      responseConverter = createResponseConverter();

      if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
        throw methodError(method, "HEAD method must use Void as response type.");
      }

      return new HttpServiceMethod<>(this);
    }

这里面干了不少事情,创建了适配器,转换器,这两个其实就是从我们retrofi那两个集合里面取出来的,我们开始设置的适配器和转换器都是存入这两个集合的,还获取了方法的返回类型。最好创建了一个HttpServiceMethod对象,下面是它的构造方法:

  HttpServiceMethod(Builder<ResponseT, ReturnT> builder) {
    requestFactory = builder.requestFactory;
    callFactory = builder.retrofit.callFactory();
    callAdapter = builder.callAdapter;
    responseConverter = builder.responseConverter;
  }

到这里loadServiceMethod(method).invoke(args)这段代码的前半部分loadServiceMethod(method)已经分析完了,到最后返回一个HttpServiceMethod对象,最后调用invoke方法这段我们看看干了什么,invoke()是HttpServiceMethod这个类的方法:

  @Override ReturnT invoke(@Nullable Object[] args) {
    return callAdapter.adapt(
        new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
  }

callAdapter就是设置的适配器,我们看到我们分析的代码流程中没有设置,这个时候你是否还记得第一篇讲的在适配器集合中retrofit会默认给我们添加一个,所以callAdapter就是从集合中取出来的,retrofit默认添加的是ExecutorCallAdapterFactory这个适配器,所以现在我们就去看看它的adapt方法:

   @Override public Call<Object> adapt(Call<Object> call) {
        return new ExecutorCallbackCall<>(callbackExecutor, call);
      }

就是这个,没干什么,创建了一个ExecutorCallbackCall对象,我们看一下它的构造方法:

    ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
      this.callbackExecutor = callbackExecutor;
      this.delegate = delegate;
    }

保存了两个参数,一个是Executor 回掉线程,一个是用于真正请求的call对象。

Response<User> user = api.getUser().execute();

上面所有的分析都是api.getuser()这个方法的过程,最后一步是.execute(),方法,这个方法就是ExecutorCallbackCall对象的方法:

  @Override public Response<T> execute() throws IOException {
      return delegate.execute();
    }

最后调用了Call的execute()。到此基本整个流程就走完了。

总结:

retrofit这两篇主要是通过用法深入到源码了解整个流程。这其中还有很多细节,后续分析。

相关文章

网友评论

      本文标题:Retrofit源码分析(二)

      本文链接:https://www.haomeiwen.com/subject/zgdsvftx.html