我正在扩展默认的 Retrofit 2 回调:
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 ...
}
}
如何将 Response 的通用类型向下转换为我自己的类? 这个过程应该是自动的吗?我正在为客户端使用 GsonConverter。
最佳答案
我认为你必须修改 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();
关于java - 改造自定义回调通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46932671/