Java泛型不能使用instanceof運算符

因為編譯器使用類型擦除,運行時不會跟蹤類型參數,所以在Box <Integer>Box <String>之間的運行時差異無法使用instanceOf運算符進行驗證。所以類似下麵的代碼用法是錯誤的 ~!

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>){ }

上一篇: Java泛型不能轉換類型 下一篇: Java泛型不能使用數組