Because generic type information is erased at runtime, it is illegal to use the instanceof
operator on parameterized types other than unbounded wildcard types.
I extract this statement from effective java edition 2. And it says that preferred way to use instanceOf is :
// Legitimate use of raw type - instanceof operator
if (o instanceof Set) { // Raw type
Set<?> m = (Set<?>) o; // Wildcard type
...
}
Can some body please explain the concept ?(I understood the reified and erasure concepts)
If you understood how erasure works, you know that
instanceofhas no way to check for the erased type, so it can only be used with the raw type.Along the same lines, after you have established that the object is some sort of Set, you cannot be sure what kind of type the Set has. So you can only (safely) use
Set<?>(which means that everything you pull out from the Set cannot be narrowed down to more thanObject, and you cannot put in anything at all).