[英]Java Casting query Exception and error
在Java中,什么時候會出現不兼容的類型編譯錯誤,什么時候會出現ClassCastException?
ClassCastException API規范明確指出:
拋出該異常以指示代碼已嘗試將對象強制轉換為不是實例的子類。
ClassCastException在運行時發生,因為編譯器認為強制轉換可能是有效的。
例如:
// The below line will compile but ClassCastException will be raised at runtime
Integer i = (Integer) new Object();
不兼容的類型錯誤很容易由編譯器在編譯時自行解決。 它只是看您要向其投射特定對象的類是否屬於同一層次結構。
例如:
String str = "abc"; <br>Integer number = (Integer) str;
// Compile Error : Integer and String are not in the same hierarchy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.