我的代碼:即使我知道它正確返回,爲什麼我必須轉換爲泛型類型T?
private static <T> T get(Class<T> clazz) throws IllegalAccessException, InstantiationException {
if (clazz.equals(String.class)) {
return (T) new String("abc");//line x
} else {
return clazz.newInstance();
}
}
正如你看到的,在line x
,T
必須String.class
並返回String
。但編譯失敗而不會將結果投射到T
。
變化line x
變爲return new String("abc");
結果Incompatible types
。
這實際上不是模板的意思。當然,對你來說顯然它會一直返回類型T的東西 - 但是編譯器很明顯嗎?如果T不是字符串,仍然有一些途徑(可以訪問或不可訪問)返回錯誤的類型。 – JArkinstall