在java中,什么时候我们会得到不兼容的类型编译错误,什么时候会得到ClassCastException?
最佳答案
ClassCastException API 规范明确指出:
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
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
关于Java Casting 查询异常和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23197564/