為什么Javac會抱怨與類的類型參數(shù)無關(guān)的泛型?請按順序閱讀代碼中的注釋,那里的問題詳細(xì)信息。為什么會發(fā)生這種差異?如果可能,請引用JLS。import java.util.*;/**
* Suppose I have a generic class
* @param <T> with a type argument.
*/class Generic<T> {
// Apart from using T normally,
T paramMethod() { return null; }
// the class' interface also contains Generic Java Collections
// which are not using T, but unrelated types.
List<Integer> unrelatedMethod() { return null; }}@SuppressWarnings("unused")public class Test {
// If I use the class properly (with qualified type arguments)
void properUsage() {
Generic<String> g = new Generic<String>();
// everything works fine.
String s = g.paramMethod();
List<Integer> pos = g.unrelatedMethod();
// OK error: incompatible types: List<String> := List<Integer>
List<String> thisShouldErrorCompile = g.unrelatedMethod();
}
// But when I use the raw type, *ALL* the generics support is gone, even the Collections'.
void rawUsage() {
// Using Generic<?> as the type turns fixes the warnings below.
Generic g = new Generic();
// OK error: incompatible types: String := Object
String s = g.paramMethod();
// WTF warning: unchecked conversion: List<Integer> := raw List
List<Integer> pos = g.unrelatedMethod();
// WTF warning: unchecked conversion: List<String> := raw List
List<String> thisShouldErrorCompile = g.unrelatedMethod();
}}邊注我最初是在IntelliJ IDEA中找到這個(gè)的,但是我猜編譯器與javac兼容,因?yàn)楫?dāng)我用下面的代碼編譯上面的代碼時(shí),它給出了相同的錯(cuò)誤/警告。$ javac -version
javac 1.7.0_05$ javac Test.java -Xlint:unchecked...$ javac Test.java -Xlint:unchecked -source 1.5 -target 1.5...
為什么Javac會抱怨與類的類型參數(shù)無關(guān)的泛型?
拉丁的傳說
2019-09-26 15:23:16