此行不會編譯:
test(E1.class,E2.class);
只有一種類型參數E
和Java必須準確推斷的參數類型相匹配。它不能推斷出Example
,因爲對象是Class<E1>
和Class<E2>
,而不是Class<Example>
。 Java泛型的不變性防止了這種情況的發生。
您可以解決此通過引入上test
的泛型類型參數的上限通配符:
public static <E extends Example> void test(Class<? extends E>... es)
這使得Java推斷Example
爲E
,通過滿足與E1
和E2
上限通配符。
第二行創建一個Class
es的原始數組,繞過泛型並生成「未經檢查的調用」警告。
new Class[]{E1.class,E2.class}
如果你試圖提供一個類型參數Class
在這裏,你會得到一個編譯器錯誤與任何中途合理的類型參數:
// Needs Class<Example> but found Class<E1> and Class<E2>
test(new Class<Example>[]{E1.class,E2.class});
// Needs Class<E1> but found Class<E2>
test(new Class<E1>[]{E1.class,E2.class});
// Needs Class<E2> but found Class<E1>
test(new Class<E2>[]{E1.class,E2.class});
通過使用通配符通過滿足推理這裏只是揭示了真正的問題 - 通用數組的創建。
// Generic array creation
test(new Class<? extends Example>[]{E1.class,E2.class});
非常感謝。這對我的計劃永遠不會造成傷害,但我一直在爲此撓頭。我非常感謝澄清。 – Squirvin 2014-10-03 01:47:53