您好,我正在使用 java 8
。案例如下:
我有一个空接口(interface)AsyncResponse
,如下所示:
package com.personal.carrot.core.models;
public interface AsyncResponse {
}
我有一个模型APIResponse
package com.personal.carrot.core.models;
import org.codehaus.jackson.annotate.JsonProperty;
public class APIResponse implements AsyncResponse {
@JsonProperty("numberOfFeatures")
public Long numberOfFeatures;
}
最后,我有了一个使用 Retrofit2
来生成 API 响应的服务:
public interface APIRepository {
@POST("MYURL")
Call<APIResponse> resolveCounts(@Body HashMap<String, String> body);
}
现在,当我像下面这样调用 APIRepository 时:
Call<AsyncResponse> request = repository.resolveCounts(payload);
我得到一个错误:
java: incompatible types: retrofit2.Call (com.personal.carrot.core.models.APIResponse) cannot be converted to retrofit2.Call(com.personal.carrot.core.models.AsyncResponse)
最佳答案
失败是因为您无法分配 Call<APIResponse>
到 Call<AsyncResponse>
.通用类型是不变的。
您可能必须使用 APIResponse
作为变量的类型参数:
Call<APIResponse> request = repository.resolveCounts(payload);
那不是因为您无法设计代码来使用接口(interface) AsyncResponse
,但是因为(我在这里假设)框架使用返回类型来处理与内容类型相关的绑定(bind)。
关于java - 不能将父类型用作变量类型,但仍可以接收子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54340102/