問題:
先來看一段代碼:
public static void main(String[] args) {
int i = 0 ;
Object x = i;
System.out.println((String) x);
}
雖然再代碼編譯階段,編譯器並不會報任何異常,但是如果運行起來我們會發現會有如下錯誤:Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String。
描述:
從jdk文檔中我們找到如下描述:
public class ClassCastException extends RuntimeException
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
我們可以看到ClassCastException是一個運行時錯誤。導致該異常的原因是,我們將一個Object向下轉型的時候指向了一個錯誤的類型。
由此可將,向下轉型確實存在不安全因素。我們再使用向下轉型的時候,一定要注意相關問題。
相關問題:
我們都知道int是基本數據類型。當把基本數據類型賦值給Objcet對象的時候會發生如下轉換:
- 將基本數據類型int自動裝箱爲Integer對象。
- 將Integer對象向上轉型爲Objcet對象。