gpt4 book ai didi

java - 与 T 不兼容的类型

转载 作者:行者123 更新时间:2023-12-01 06:05:48 24 4
gpt4 key购买 nike

我有一个名为 adapt 的方法,但我不知道 T 和 ? 之间的确切区别。

对我来说,适应必须接受任何类(class)

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);
}
}
}

但是我无法传递这个处理程序。为什么会出现这种情况?

错误

incompatible types: inferred type does not conform to equality constraint(s) [ERROR] inferred: java.lang.Object [ERROR] equality constraints(s): java.lang.Object,com.daniela.infra.RequestorResponse

最佳答案

似乎您正在尝试传递定义的类 RequestorResponse转换为泛型类型 this.adapt(handler)

ResponseHandler < RequestorResponse > handler

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){

这里有一些引用:

  1. <T>通用类型:https://docs.oracle.com/javase/tutorial/java/generics/types.html
  2. <?>通配符:https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

关于java - 与 T 不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com