retrofit自从面世,一直很火,现在大多android开发的都在用的网络框架。我们在设置retrofit的时候需要设置CallAdapterFactory
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://www.stonebangbang.com/test.php/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.creat()) .build(); return retrofit.create(apiServiceClass);
这是用rxjava自定义的adapter来实现的,我们一般都是这么用,但是如果我们要自定义calladapter的时候该怎么做呢?现在我们来看看calladapter是干什么的
这是一个抽象类,我们需要实现get方法,先来看看这几个方法都是干嘛的。abstract class Factory { /** * Returns a call adapter for interface methods that return {@code returnType}, or null if it * cannot be handled by this factory. */ public abstract @Nullable CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit); /** * Extract the upper bound of the generic parameter at {@code index} from {@code type}. For * example, index 1 of {@code Map<String, ? extends Runnable>} returns {@code Runnable}. */ protected static Type getParameterUpperBound(int index, ParameterizedType type) { return Utils.getParameterUpperBound(index, type); } /** * Extract the raw class type from {@code type}. For example, the type representing * {@code List<? extends Runnable>} returns {@code List.class}. */ protected static Class<?> getRawType(Type type) { return Utils.getRawType(type); } }
getParameterUpperBound
首先getParameterUpperBound方法,他是获取参数的type的,我觉得可以把它理解为获取的泛型,比如我们写了个User<T>,我们可以new User<Man>这个man就是我们实例化的type。在看这个方法,他有两个参数,一个是index,是指位置,比如我们的User<T,V> 这个T就是0,这个V就是1,parameterizedType是个接口,继承type接口,从字面上来看是参数类型,所以我把它理解为我们定义的这个T的类型,比如man,比如我们传入的任何实例,如果我们没有传入那就不是parameterizedtype类型的。
而getRawType是提取的实例class,如果我们的User<T> 他得到的就是User.class。
而get方法是返回一个calladapter,所以我们要顶一个calladatper,再来看下calladapter,
public interface CallAdapter<R, T> { /** * Returns the value type that this adapter uses when converting the HTTP response body to a Java * object. For example, the response type for { @code Call<Repo>} is { @code Repo}. This type * is used to prepare the { @code call} passed to { @code #adapt}. * <p> * Note: This is typically not the same type as the { @code returnType} provided to this call