簡體   English   中英

Map 在分配 Map.class 時是原始類型。 但是分配類型會導致不匹配。 如何參數化 Map.class?

[英]Map is a raw type when assigning Map.class. But assigning a type results in a mismatch. How do I parameterize Map.class?

我在這里收到一條警告,指出 Map 是原始類型。

// Map is a raw type. References to generic type Map<K,V> should be parameterized
Class<Map> c = Map.class;

但是如果我參數化類型,那么我會得到一個不匹配的結果:

// Type mismatch: cannot convert from Class<Map> to Class<Map<Object,Object>>
Class<Map<Object, Object>> c = Map.class;

我嘗試了一些變化,但我找不到任何方法來參數化表達式的右側( Map.class )以滿足左側,這是參數化的。

在這種情況下,如何參數化Map.class

在這種情況下,我將它傳遞給帶有簽名的方法:

public <T> T method(Class<T> type) {
   return (T) otherMethod(type);
}

我只想提供Map類型,因為我不知道內部使用的是哪種map,這個細節並不重要。 我正在嘗試解決調用該方法時收到的警告:

// Type safety: The expression of type Map needs unchecked conversion to conform to Map<String,Object>
Map<String, Object> a = method(Map.class);

Map.class屬於Class<Map> ,它不是Class<Map<Object, Object> 你可以使用Class<? super Map<Object, Object>> c = Map.class; Class<? super Map<Object, Object>> c = Map.class; ,因為每個Map<Object, Object>也是Map (但不是相反)

這會抑制呼叫站點的警告:

public static <T> T method(Class<? super T> type) {
    return (T) otherMethod(type);
}

表達式(T) otherMethod(type)上仍然存在未經檢查的強制轉換警告,但我相信這是不可避免的。

暫無
暫無

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

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