content: package me.andydev.retrofit.lifecycle;
  
  import java.lang.reflect.Constructor;
  
  import me.andydev.retrofit.lifecycle.common.Cancellable;
  import retrofit2.Call;
  
  
  /**
   * Description: Manage Call's lifecycle by a proxy class
   * Created by Andy on 2017/7/4
   */
  
  public class RetrofitLifecycle {
  
      /**
       * Get proxy class for given retrofitAPI, which will take care of Call's lifecycle
       *
       * @param retrofitAPI          api interface that defines the request
       * @param retrofitAPIImplement api implementation generated by retrofit(result of Retrofit.create())
       * @param <T>                  api interface that defines the request
       * @return proxy class that takes care of Call's lifecycle
       */
      public static <T> T getProxyInterface(Class<T> retrofitAPI, T retrofitAPIImplement) {
          if (retrofitAPIImplement == null) {
              throw new NullPointerException("retrofitAPIImplement can not be null");
          }
  
          String className = retrofitAPI.getName();
          if (className.startsWith("android.") || className.startsWith("java.")) {
              throwsProxyClassNotFoundException(className);
          }
  
          T proxyClassInstance = null;
          try {
              Class<?> bindingClass = Class.forName(className + "InvokeProxy");
              Constructor<T> constructor = (Constructor<T>) bindingClass.getConstructor(retrofitAPI);
              proxyClassInstance = constructor.newInstance(retrofitAPIImplement);
          } catch (Exception e) {
              e.printStackTrace();
              throwsProxyClassNotFoundException(className);
          }
          return proxyClassInstance;
      }
  
      /**
       * Cancel all Calls of the given proxy class
       *
       * @param retrofitAPI proxy class that returned by getProxyInterface()
       * @param excludes    Calls not to be cancelled
       */
      public static void cancelAll(Object retrofitAPI, Call... excludes) {
          if (retrofitAPI instanceof Cancellable) {
              ((Cancellable) retrofitAPI).cancelAll(excludes);
          } else {
              throw new IllegalArgumentException(retrofitAPI.getClass().getName() + " must implement Cancellable");
          }
      }
  
      private static void throwsProxyClassNotFoundException(String className) {
          throw new IllegalArgumentException("Cannot find proxy class for " + className
                  + ". Did you forget to add @RetrofitInterface to it?");
      }
  }
  