Java Casting 查询异常和错误

标签 java casting

在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/

相关文章:

java - HTTP 状态 500 - java.lang.NoClassDefFoundError : java/time/temporal/TemporalField when run app on OpenShift

java - 如何解决界面中似乎需要 setter 的情况?

java - 是否可以将图像传输到 3 个不同的 Activity ?

java - 动态 JPA 连接

iphone - 从 iphone 应用程序的 xcode 中的字符串获取 ascii 代码

c# - 转换值类型常量

c - 类型安全与松散类型 - GO 与 C

vb.net - InvalidCastException 未处理?

c - C 中的指针类型转换 "on the fly"

java - 多个 Tomcat 8 安装或虚拟主机