In the code extracted from Java Complete Reference by Herbert Schildt:
class Gen<T> {
T obj;
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
class Test {
public static void main(String args[]) {
Gen2<Integer> obj = new Gen2<Integer>(99);
}
}
he mentions that instanceof can't verify if a object is from a typed generic class at runtime because no Generic information is available:
if (obj instanceof Gen2<Integer>) // illegal, doesn't compile
you can only use
if (obj instanceof Gen2<?>) // legal
However, you can still Cast the same object to (Gen) as long as it is compatible:
(Gen<Integer>) obj // legal
but:
(Gen<Long>) obj // illegal
Isn't this a Java contradiction? If Java knows that obj can be cast to a Gen at runtime, why doesn't it knows that obj is an instanceof Gen class/subclass?