我有一种名为 adapt 的方法,我不确切知道T和?之间的区别。
对我来说, adapt 必须接受任何类。
public void getRequestor(Long requestorId, ResponseHandler<RequestorResponse> handler){
String url = this.serviceUrl;
//Error happens in this.adapt...
RestClient.url(url).get(null).onResponse(this.adapt(handler), RequestorResponse.class);
}
private <T> RestClient.ResponseHandler<T> adapt(ResponseHandler<T> handler){
return new RestClient.ResponseHandler<T>() {
@Override
public void onResponse(ResponseEntity<T> response) {
if(response.getStatusCode().is2xxSuccessful()) {
handler.onResponse(response.getBody());
return;
}
handler.onError(new com.sensedia.api.interfaces.Error(String.valueOf(response.getStatusCodeValue())));
}
};
}
RestClient类
public class RestClient {
private final String url;
private RestClient(String url) {
this.url = url;
}
public static RestClient url(String url) {
return new RestClient(url);
}
//Others methods
@FunctionalInterface
public interface ResponseHandler<T> {
void onResponse(ResponseEntity<T> var1);
}
public static class PagedOperation<T> extends AbstractOperation<T, RestClient.PagedOperation<T>> {
private final RestClient.Limit limit;
private final RestClient.Offset offset;
public PagedOperation(String url, RestClient.Limit limit, RestClient.Offset offset) {
super(url);
this.limit = limit;
this.offset = offset;
}
public void onResponse(RestClient.ResponseHandler<T> handler, Class<T> type) {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.url()).queryParam("_limit", new Object[]{this.limit.get()}).queryParam("_offset", new Object[]{this.offset.get()});
ResponseEntity<T> response = this.client().getForEntity(builder.build().encode().toUri(), type);
handler.onResponse(response);
}
}
}
但我无法通过此处理程序。为什么会这样?
错误
不兼容的类型:推断类型不符合相等性 constraint(s)[ERROR]推断:java.lang.Object [ERROR]相等 constraints(s):java.lang.Object,com.daniela.infra.RequestorResponse
答案 0 :(得分:-1)
好像你试图将定义的类RequestorResponse
传递给泛型类型this.adapt(handler)
ResponseHandler&lt; RequestorResponse&gt;处理
Java不允许您这样做,因为您的通用类型T
可能与RequestorResponse
不同,
我建议你这样做
public void getRequestor(Long requestorId, ResponseHandler<T> handler){
String url = this.serviceUrl;
RestClient.url(url).get(null).onResponse(this.adapt(handler), RequestorResponse.class);
}
或者将this.adapt更改为
private <T> RestClient.ResponseHandler<T> adapt(ResponseHandler<?> handler){
这里有一些参考文献: