Java Generics – No instanceOf

Java Generics - No instanceOf

This topic is about Java Generics – No instanceOf.

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

In this topic we learned about Java Generics – No instanceOf. To know more, Click Here.

Leave a Reply