[英]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.