In the code snippet below, why does 1 not produce a run-time Exception as I am trying to cast Class>B> to Class>A>?
package example;
Class A {
public A() {
}
}
Class B extends A {
public B() {
}
}
public static void main() {
Class<A> c = null;
//1. Does not produce exception at run-time even though I cast Class<B> to Class<A>
try {
c = (Class<A>) Class.forName("example.B");
} catch (ClassNotFoundException e) {
}
//2. Compile time error: Cannot Cast Class<B> to Class<A>
c = (Class<A>) B.class; //Error
}
Class.forName()returnsClass<?>, which is roughly equivalent toClass(without generics).The second version will also compile if you add another non-generic cast inbetween:
However, this can’t be right, so the compiler saves you from this error. In the first version, it can’t do that.