在下面的代碼片段中,爲什麼1不會生成運行時異常,因爲我試圖將Class> B>轉換爲Class> A>?Class Literal vs Class.forname + Java Generics
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
}
它*可能*拋出一個ClassNotFoundException。有了這種異常處理,你永遠不會知道。 – EJP
哦,其實我已經在打印內打印了,只是忘了在我的問題中添加它。放心吧,沒有ClassNotFoundException –