简体   繁体   English

Java Casting查询异常和错误

[英]Java Casting query Exception and error

在Java中,什么时候会出现不兼容的类型编译错误,什么时候会出现ClassCastException?

ClassCastException API Specifications clearly says: 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 occurs at runtime because compiler believes that the cast may be a valid one. ClassCastException在运行时发生,因为编译器认为强制转换可能是有效的。

Eg: 例如:

// The below line will compile but ClassCastException will be raised at runtime
Integer i = (Integer) new Object();

Incompatible type error can easily be resolved by the compiler at compile time itself. 不兼容的类型错误很容易由编译器在编译时自行解决。 It simply looks if the class to which you are trying to cast a specific object falls in the same hierarchy. 它只是看您要向其投射特定对象的类是否属于同一层次结构。

Eg: 例如:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM