2017-07-13 96 views
1

我有這種方法調用適應,我不知道T和?之間的確切區別。與T不兼容的類型

對我來說,改編必須接受任何類別

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

但我不能接受這處理。爲什麼會發生?

錯誤

不兼容的類型:類型推斷出不符合平等 約束(s)實施ERROR]推斷:java.lang.Object中[ERROR]平等 約束(或多個):java.lang中。對象,com.daniela.infra.RequestorResponse

+1

是什麼'this'指什麼? – marstran

+0

你在那裏打電話的「onResponse」方法的定義是什麼?這不是你顯示更高的那個,這個有兩個參數。 –

+0

RestClient是一個使用Spring的RestTemplate的類,它很容易使用API​​進行分頁。 –

回答

-1

好像你正試圖定義的類RequestorResponse傳遞到泛型類型this.adapt(handler)

ResponseHandler所< RequestorResponse>處理

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

或者將此變更爲

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
+0

爲什麼我的anwser被downvoted? –