簡體   English   中英

Java 非泛型方法隱藏具有交集類型的泛型方法

[英]Java non-generic method hiding generic method with intersection types

如果三個公共接口定義為:

public interface One{}
public interface Two{}
public interface Three{}

而另一個class,Super,定義為:

public class Super {
    public static <E extends One & Two & Three> void hmm(E item) {}
}

為什么 Super 的以下子類會出現編譯錯誤?

public class Subber extends Super{
    public static void hmm(One item) {}
}

我希望上述方法可以簡單地隱藏 Super 的方法,但似乎並非如此。

JLS (8.4.8.2) 說:

If a class C declares or inherits a static method m, then m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of C 否則可以訪問(第 6.6 節)以在 C 中進行編碼。

其中子簽名在 8.4.2 中定義為:

如果兩個方法或構造函數 M 和 N 具有相同的名稱、相同的類型參數(如果有)(第 8.4.4 節),並且在將 N 的形式參數類型調整為類型參數之后,則它們具有相同的簽名的 M,形參類型相同。

方法 m1 的簽名是方法 m2 簽名的子簽名,如果: m2 與 m1 具有相同的簽名,或者 m1 的簽名與 m2 簽名的擦除(第 4.6 節)相同。

根據 JLS 4.6,類型變量的擦除是其最左邊界的擦除,所以:據我了解,Subber 的 hmm 方法與 Super 的 hmm 方法的擦除相同,因此將是 Super 的 hmm 的子簽名,因此意味着它會隱藏 Super 的嗯。 但是,我收到的錯誤消息(來自 eclipse),鑒於上述情況,這似乎沒有意義:“Subber 類型的方法 hmm(One) 與 Super 類型的 hmm(E) 具有相同的擦除,但沒有把它藏起來。” 我錯過了什么?

編輯:精確的錯誤消息,其中主要方法只包含Subber.hmm(null); 是:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    Name clash: The method hmm(One) of type Subber has the same erasure as hmm(E) of type Super but does not hide it

    at base/testpack4.Subber.hmm(Subber.java:4)
    at base/testpack4.Main.main(Main.java:5)

有人可以引用可靠的來源(最好是 JLS)解釋為什么 Subber 的方法無法編譯嗎?

……有人能解釋一下為什么 Subber 的方法無法編譯嗎……

實現了您列出的代碼 逐字逐句 compiles fine with a call to and .我的通過調用編譯得很好。

interface that meets the requirements of the type parameter section of .我唯一不同的是引入了一個新的接口,它滿足的類型參數部分的要求。

into to confirm that wasn't being called;然后我將的實例傳遞給以確認沒有被調用; 證明它實際上是隱藏的。

...引用可靠來源(最好是 JLS)?...

該實現的行為與您引用的 JLS 規范完全相同。

E 的類型仍然未定義,您可以 go 並通過設置 Super class 的 E 泛型對其進行參數化,並在 Subber class 中定義它:

public class Super<E> {
    public static <E extends One & Two & Three> void hmm(E item) {}
}

public class Subber extends Super<One> {
    public static void hmm(One item) {}
}

暫無
暫無

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

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