Java ใช้ Type Erasure เพื่อรองรับ Generics และตรวจสอบชนิดข้อมูลอย่างเข้มงวดขณะคอมไพล์ แล้วลบข้อมูลชนิดออกระหว่างรันไทม์
กลไกการทำงาน
- พารามิเตอร์ชนิดใน generic type ถูกแทนที่ด้วย bound (ถ้ามี) หรือ
Object(ถ้า unbounded) - bytecode จึงมีแค่ class, method, interface ธรรมดา - แทรก type cast เพื่อรักษาความปลอดภัยของชนิด
- สร้าง bridge methods เพื่อรักษา polymorphism ใน generic types ที่สืบทอด
ตัวอย่าง: Raw Type และ Type Erasure
import java.io.PrintStream;
import java.util.*;
public class Demo {
public Demo() {}
public static void main(String args[]) {
List myList = new ArrayList(); // raw type
myList.add("Hi there");
String myStr;
for (Iterator iter = myList.iterator(); iter.hasNext();
System.out.println(myStr)) {
myStr = (String) iter.next(); // cast จำเป็นเพราะ type erasure
}
}
}
ผลลัพธ์
Hi there
คำอธิบาย: ใช้ raw type List แทน List Iterator คืนค่า Object ต้อง cast เป็น String เอง นี่คือผลของ type erasure - ข้อมูล generic ถูกลบออก รันไทม์รู้แค่เป็น List ของ Object
ข้อควรระวัง
- ไม่สามารถใช้
instanceofกับ parameterized type ได้ (เช่นlist instanceof Listcompile error) - ไม่สามารถสร้าง array ของ parameterized type ได้ (เช่น
new List)[10] - Overloading method ที่แตกต่างกันแค่ generic parameter ไม่ได้ (erasure ทำให้ signature เหมือนกัน)