public class Foo<T extends Bar>{
private Class<T> _type;
public Foo(Class<T> _type){
this._type = _type;
}
public Collection<T> hypothetical(List<T> items){ //PROBLEMATIC
return dostuffWithItems(items);
}
}
用法:差異在通用參數多態性
Foo<? extends ChildBar> foo = new Foo<ChildBar>(ChildBar.class);
List<ChildBar> items = (List<ChildBar>) foo.hypothetical(new ArrayList<ChildBar>()); //COMPILER ERROR: The method hypothetical(List<capture#2-of ?>) in the type Foo<capture#2-of ?> is not applicable for the arguments (List<ChildBar>)
,編譯器將要麼接受
鑄造List<ChildBar> items
參數List<?>
或改變hypothetical(List<T> items)
簽名要麼
一)hypothetical(List<ChildBar> items)
或
b)hypothetical(List<? extends Bar> items)
但是,沒有任何替代方法確保假設方法的List items參數T type是Foo class T參數類型的等效運行時類型。我目前正在使用一種額外的方法來驗證參數類型。 在沒有額外邏輯的情況下,Java泛型構造中是否有更好的方法自動實現這一點?或者更好的是,爲什麼我不能將foo聲明爲Foo<? extends Bar>
,然後在運行時填寫實際的類型參數?
'foo.hypotethical(new ArrayList())'有什麼問題? –
你應該通過'類 clazz'作爲參數:'收集假設(列表項目,類 clazz)' –
我發現3錯誤:1)'dostuffWithItems'是未定義的。 2)「假設」,「低估」和「假設」拼寫不一樣。 3)返回類型'Collection'不能被分配給'List'。 ---你也有這些_PROBLEMATIC_嗎?因爲一旦我修復這些3,我沒有編譯錯誤。 – Andreas