Retrofit 源码分析

168 阅读1分钟

retrofit 初始化:

 public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service); //1
    if (validateEagerly) {
      eagerlyValidateMethods(service);//2
    }
    //3 
    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);
            }
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.adapt(okHttpCall);
          }
        });
  }

(按照代码中的标签来解释每行代码的作用)

  1. 检查是否为合法接口(未继承其他接口)。
  2. 直接生成ServiceMethod。
  3. 动态代理。接口中方法的具体实现委托给ServiceMethod类,retrofit 的主要作用也是通过更简洁的代码来构造HTTP请求。

java.lang.reflect.Proxy:该类用于动态生成代理类,只需传入目标接口、目标接口的类加载器以及InvocationHandler便可为目标接口生成代理类及代理对象。