Java泛型無界類型擦除
如果使用無界類型參數,則Java編譯器將使用Object
替換類型參數。
示例
創建一個名稱爲:UnboundedTypesErasure.java 文件,並編寫以下代碼 -
package com.yiibai.demo2;
public class UnboundedTypesErasure {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(1000));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
在本示例中,java編譯器將用Object
類替換T
,而在類型擦除之後,編譯器會爲以下代碼生成字節碼。
package com.yiibai.demo2;
public class UnboundedTypesErasure {
public static void main(String[] args) {
Box integerBox = new Box();
Box stringBox = new Box();
integerBox.add(new Integer(1000));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%d\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
class Box {
private Object t;
public void add(Object t) {
this.t = t;
}
public Object get() {
return t;
}
}
在這兩種情況下,執行輸出結果是相同的 -
Integer Value :1000
String Value :Hello World