1 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
您實際上已經(jīng)回答了您的問題:如果類型不受限制,則擦除是第一個邊界或?qū)ο蟆W屛覀兛磶讉€例子:
public class A implements Serializable {
// since the first bound is Cloneable, the erasure is Cloneable
static <T extends Cloneable & Serializable> void doSomething1(T t) {}
// since the first bound is Serializable, the erasure is Serializable
static <T extends Serializable & Cloneable> void doSomething2(T t) {}
// since T is not bounded, the erasure is Object
static <T> void doSomething(T t) {
System.out.println("A");
}
// the type of A is a class, so it has to come first
// the erasure is A since it comes first
static <T extends A & Serializable> void doSomething(T t) {
System.out.println("B");
}
// not possible because the bounds are two classes
// static <T extends Object & A> void doSomething(T t) {return null;}
}
由于擦除不同,方法可以具有相同的名稱!但這是完全不推薦的,而且相當令人困惑,因為行為發(fā)生了變化:
public static void main(String[] args) {
A.doSomething(new Object()); // prints "A"
A.doSomething(new A()); // prints "B"
}
編輯后回答您的問題:不,這并不多余。指定類型參數(shù)需要實現(xiàn)的類型使您可以訪問邊界的方法。讓我們看一下下面的例子:
public final class Box<T extends A & Comparable<T>> {
private T item1;
private T item2;
int compare() {
// this is the compare method of Comparable interface
return item1.compareTo(item2);
}
}
從上面的示例中您可以看到它A沒有實現(xiàn)該Comparable接口。這意味著,如果您只是編寫,則無法簡單地比較使用該方法Box<T extends A>中的兩項,因為沒有實現(xiàn)。如果您希望框項屬于類并實現(xiàn)接口,則需要指定兩個邊界。BoxcompareToAComparableA Comparable
A實現(xiàn)的不是參考Comparable,而是T參考!即使刪除了T extends A & Comparable<T>will,A編譯器仍然可以在較低級別上執(zhí)行轉(zhuǎn)換。這就是這里正在發(fā)生的事情。如果您使用使用checkcastjavap指令的實用程序檢查字節(jié)碼,您可以看到這一點:
int compare();
....
0: aload_0
1: getfield #7 // Field item1:LA;
4: checkcast #13 // class java/lang/Comparable
7: aload_0
8: getfield #15 // Field item2:LA;
11: invokeinterface #18, 2 // InterfaceMethod java/lang/Comparable.compareTo:(Ljava/lang/Object;)I
16: ireturn
....
添加回答
舉報