You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Retrofit泛型方法无数据返回及参数错误问题

解决方案

1. 修正接口定义

把RestInterfaceController中的getData方法改为泛型方法,返回Call<T>类型——无需额外参数,因为接口的HTTP请求路径固定,泛型仅用于指定响应解析的目标类型:

public interface RestInterfaceController {
    @GET("Europe/Istanbul")
    <T> Call<T> getData();
}

2. 调整泛型方法调用

在RetrofitApply方法中,直接调用泛型版本的getData,无需强制类型转换(接口方法的泛型会和当前方法的<T>自动绑定):

private <T> void RetrofitApply(Class<T> responseType) {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.constants.baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RestInterfaceController restInterfaceController = retrofit.create(RestInterfaceController.class);
    // 直接获取对应泛型的Call实例,无需强转
    Call<T> call = restInterfaceController.getData();

    call.enqueue(new Callback<T>() {
        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if (response.isSuccessful()) {
                T responseData = response.body();
                if (responseData != null) {
                    System.out.println("DATA : " + responseData);
                    System.out.println("ERROR CODE : " + response.code());
                    System.out.println("ERROR MESSAGE: " + response.message());
                } else {
                    System.out.println("Response data is null.");
                }
            } else {
                System.out.println("Response is not successful. : " + response.code());
            }
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            System.out.println("ERROR MESSAGE : " + t.getMessage());
        }
    });
}

3. 调用泛型方法

调用RetrofitApply时传入目标模型类的Class对象即可,示例:

RetrofitApply(Example.class);

问题根源说明

  • 最初的错误是接口方法未声明泛型,且错误地尝试传递参数(原接口getData无参数定义);
  • 后续改成返回Object破坏了Retrofit的Call回调机制,导致无法正常发起请求和解析响应;
  • Retrofit结合GsonConverterFactory会自动根据Call<T>中的泛型T解析响应JSON,无需手动将Class<T>传递到接口方法中。

内容的提问来源于stack exchange,提问作者avcismail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:57:40