Java 泛型 - 無instanceOf



由於編譯器使用型別擦除,執行時也不會保留型別引數的記錄,因此執行時無法使用instanceOf運算子驗證Box<Integer>和Box<String>之間的差異。

Box<Integer> integerBox = new Box<Integer>();

//Compiler Error:
//Cannot perform instanceof check against 
//parameterized type Box<Integer>. 
//Use the form Box<?> instead since further 
//generic type information will be erased at runtime
if(integerBox instanceof Box<Integer>) { }
廣告