簡體   English   中英

Class 類型的泛型變量

[英]Class type of generic variable

我的數據結構看起來或多或少像這樣

class ResponseWrapper<T> {
    T response;

    public ResponseWrapper(T response) {
        this.response = response;
    }
}

以及處理從 JSON 讀取響應到實際 DTO 的服務。

public class GenericService<T> {
    public ResponseWrapper<T> read(String json, Class<T> clazz) throws Exception {
        T response = new ObjectMapper().readValue(json, clazz);
        return new ResponseWrapper<>(response);
    }
}

我可以這樣稱呼它:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value", SomeData.class)

我想要實現的是:

GenericResponse<SomeData> response = new GenericService<SomeData>().read("json value")

我想知道,這真的可能嗎? 這顯然行不通

  public ResponseWrapper<T> read(String json) throws Exception {
        T response = new ObjectMapper().readValue(json, T.class);
        return new ResponseWrapper<>(response);
    }

不,這是不可能的。

Java generics 通過類型擦除工作......這意味着與泛型類型參數關聯的實際 class 在運行時不可用。 如果您的代碼需要知道 class,則需要明確傳遞Class object。

而且,是的, T.class是編譯錯誤。

而且,是的,沒有辦法獲得T的 class 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM