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泛型不能使用数组

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程