2012-01-30 99 views
1

我得到了以下異常試圖在接口(實際的代碼減少到一般的例子)介紹一些仿製藥:泛型通配符再次。

Type mismatch: cannot convert from capture#1-of ? extends Interface2<:? extends Interface1> to Interface2<:Interface1>

的呼叫失敗是:

Interface2<Interface1> interface2Instance = interface1Instance.getInterface2ImplementorClass().newInstance(); 

這些是接口定義:

public interface Interface1{ 
    Class<? extends Interface2<? extends Interface1>> getInterface2ImplementorClass(); 
} 

public interface Interface2<T extends Interface1> { 
    public Object execute(T first, OtherClass1 second, OtherClass2 third, 
     OtherClass3 baseTimeFormat) throws ChartScriptException; 
} 

我可以將故障線路更改爲:

Interface2<**? extends** Interface1> interface2Instance = interface1Instance.getInterface2ImplementorClass().newInstance(); 

但後來我得到的異常時,我想打電話給

interface2Instance.execute(interface1Instance, second, third, forth); 

我得到的編譯器錯誤:

The method execute(capture#3-of ? extends Interface1, OtherClass1, OtherClass2, OtherClass3) in the type Interface2<:capture#3-of ? extends Interface1> is not applicable for the arguments (Interface1, OtherClass1, OtherClass2, OtherClass3)

我找不到出路的這混亂,我錯了什麼,我在哪裏可以查看我打破的規則?

+1

您的通用類名稱使得這很難解析。今後,我推薦水果和蔬菜的名字。 – cheeken 2012-01-30 04:14:57

回答

1

想想這樣:想象一下Interface2ListInterface1Number。您撥打代碼的方式,newInstance()可能返回一個List<Integer>(因爲Integer延伸Number),但將List<Integer>分配給List<Number>是無效的。這裏的原因:

List<Integer> ints = new ArrayList<Integer>(); 
List<Number> nums = ints; //if this was possible 
nums.add(2.0); 
Integer first = ints.get(0); //then this would fail 

的技術術語,這是協方差,你可以閱讀更多關於它的Angelika Langer's Generics FAQ。總之,泛型不是協變的。

由於缺乏具體的細節,我不確定我能否提出修復建議。您可以讓getInterface2ImplementorClass()返回Class<? extends Interface2<Interface1>>而不是Class<? extends Interface2<? extends Interface1>>

+0

關於你的建議,這是行不通的,因爲我無法返回一個Interface2實現器來實現Interface1 – Kai 2012-01-30 20:59:14