Java Generics 简明教程

Java Generics - No instanceOf

由于编译器使用类型擦除,因此运行时不会跟踪类型参数,因此在运行时,使用 instanceOf 运算符不能验证 Box<Integer> 和 Box<String> 之间的差异。

Because compiler uses type erasure, the runtime does not keep track of type parameters, so at runtime difference between Box<Integer> and Box<String> cannot be verified using instanceOf operator.

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