Java 泛型无实例

创建于 2024-12-02 / 35
字体: [默认] [大] [更大]

由于编译器使用类型擦除,运行时不会跟踪类型参数,因此在运行时无法使用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>) { }


0 人点赞过