改进自定义回调通用类型

时间:2017-10-25 12:38:29

标签: java android generics retrofit retrofit2

我正在扩展默认的Retrofit 2 Callback:

abstract class APICallback<T> implements Callback<T> {

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (!response.isSuccessful()) {
            // Cast response.body() to my POJO class, results in null
            MyClass myClass = (MyClass) response.body();
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        // TODO ...
    }
}

如何将响应的泛型类型转发给我自己的类? 这个过程应该是自动的吗?我正在为客户使用GsonConverter。

3 个答案:

答案 0 :(得分:1)

我认为你必须修改AdapterFactory然后注册改装

public class APICallAdapterFactory extends CallAdapter.Factory {

@Nullable
@Override
public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
    final Type responseType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
    return new CallAdapter<Object, Object>() {
        @Override
        public Type responseType() {
            return responseType;
        }

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

 private static Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(APIService.baseUrl)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(new APICallAdapterFactory())
        .build();

答案 1 :(得分:0)

用MyClass替换T

class APICallback implements Callback<MyClass> {

    @Override
    public void onResponse(Call<MyClass> call, Response<MyClass> response) {
        if (response.isSuccessful()) {
            // Cast response.body() to my POJO class, results in null
             MyClass myClass = response.body();
        }
    }

    @Override
    public void onFailure(Call<MyClass> call, Throwable t) {

    }
}

答案 2 :(得分:0)

您可以按此处理

Gson gson = new Gson();
MyClass myClass = gson.fromJson(response.body(), MyClass.class);