Retrofit 2.0中的validateEagerly()方法(beta 2)

时间:2015-10-02 09:32:10

标签: android retrofit

validateEagerly()(Retrofit 2.0 beta 2)方法究竟做了什么? 我在哪里可以应用这种方法?

JavaDoc说When calling create on the resulting Retrofit instance, eagerly validate the configuration of all methods in the supplied interface.,但这种描述不太清楚。

2 个答案:

答案 0 :(得分:3)

validateEagerly()验证您在构建Retrofit实例时提供的配置。这将检查您的接口注释是否有效的Retrofit注释,检查参数和方法参数,如果它们与注释集一致,也会检查可能的错误方法返回类型(不同于Call<T>)。

通常在构建Retrofit实例之前调用检查。

private Retrofit getRetrofit() {
        OkHttpClient okClient = getOkHttpClient();
        GsonBuilder builder = getGsonBuilder();
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
        retrofitBuilder.client(okClient);
        retrofitBuilder.baseUrl(API_ENDPOINT);
        retrofitBuilder.addConverterFactory(GsonConverterFactory.create(builder.create()));
        retrofitBuilder.validateEagerly();
        return retrofitBuilder.build();
    }

如果某些内容无效,它可以抛出IllegalArgumentException不同的消息和原因。

答案 1 :(得分:0)

如果您希望尽快验证界面中的所有方法,您希望validateEagerly(true)

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

      // validate your all methods
  private void eagerlyValidateMethods(Class<?> service) {
    Platform platform = Platform.get();
    for (Method method : service.getDeclaredMethods()) {
      if (!platform.isDefaultMethod(method)) {
        loadServiceMethod(method);
       }
    }
   }

  //thie method will cash method in LinkedHashMap
  ServiceMethod loadServiceMethod(Method method) {
    ServiceMethod result;
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = new ServiceMethod.Builder(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }