2014-10-03 66 views
8

運行Java 1.8 的JavaSE-1.8(jdk1.8.0_20)泛型函數調用Java中沒有編制8延伸的多個接口

這個類:

public class SimpleQuestion { 

    public static void main(String[] args) { 
     DoNothing(); 
     DoNothing2(); 
     DoNothing3(); 
     DoNothing4(); 
    }  

    public interface Interface1 { 
     public void go(); 
    } 

    public interface Interface2<X> { 
     public X go2(); 
    } 

    private static <X, T extends Interface2<X> & Interface1> void DoNothing() { 
     return; 
    } 

    private static <X, T extends Interface2 & Interface1> void DoNothing2() { 
     return; 
    } 

    private static <X, T extends Interface2<X>> void DoNothing3() { 
     return; 
    } 

    private static <T extends Interface2<T> & Interface1> void DoNothing4() { 
     return; 
    }  

} 

給人的編譯錯誤:

SimpleQuestion類型中的方法DoNothing()不適用於參數()

Wh那一個而不是DoNothing2,3和4?

+11

它在Eclipse中失敗。 Oracle編譯器適用於我。我哭了錯誤! – 2014-10-03 21:06:09

+0

但是,如果您顯式提供類型參數,它就可以工作。 – 2014-10-03 21:06:35

+0

在Java7中爲我編譯好;可能是您正在使用的編譯器/ IDE中的一個錯誤 – Krease 2014-10-03 21:08:13

回答

4

錯誤消息似乎是指在section 18.5.1 of the spec中定義的算法失敗。

對於DoNothing,算法前進(使用的術語從上述鏈接)如下:

  • 類型參數是

    P1 = X

    P2 = T extends Interface2<X> & Interface1

    和I」將使用a1和a2作爲相應的推理變量。

  • 初始綁定集是

    B0 = {a1 <: Object, a2 <: Interface2<a1>, a2 <: Interface1}

  • 沒有參數,因此沒有額外的界限在該點(B2 = B0)加入。

  • a1對a1有依賴性,所以我們先試着解析a1。它有一個適當的Object的上界,所以我們將它實例化爲這個。結合a1 = Object包括添加綁定

    a2 <: Interface2<Object>

  • 接下來我們解決A2。現在,這有兩個正確的上限,所以我們實例A2他們GLB:

    a2 = Interface2<Object> & Interface1

  • 每個變量現在有一個實例,這樣的分辨率已經成功。

因此,與錯誤消息相反,DoNothing的調用應該是適用的。這似乎是Java編譯器中的一個錯誤。