簡體   English   中英

泛型函數調用未在Java 8中編譯,擴展了多個接口

[英]Generics function call not compiling in java 8 extending multiple interfaces

運行Java 1.8 JavaSE-1.8(jdk1.8.0_20)

這節課:

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()不適用於參數()

為什么是那個而不是DoNothing2,3和4?

錯誤消息似乎是指規范18.5.1節中定義的算法失敗。

對於DoNothing,算法按以下步驟進行(使用來自上面鏈接的術語):

  • 類型參數是

    P1 = X

    P2 = T extends Interface2<X> & Interface1

    我將使用a1和a2作為相應的推斷變量。

  • 初始邊界集為

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

  • 沒有參數,因此此時沒有添加額外的界限(B2 = B0)。

  • a2對a1有依賴性,因此我們嘗試首先解析a1。 它具有適當的Object上限,因此我們將其實例化。 合並a1 = Object涉及添加邊界

    a2 <: Interface2<Object>

  • 接下來,我們解決a2。 現在有兩個適當的上限,因此我們將a2實例化為它們的glb:

    a2 = Interface2<Object> & Interface1

  • 現在每個變量都有一個實例化,因此解析成功。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM