所以我想知道 Java 在什么情况下抛出 ClassCastException
以及什么时候是“不可转换类型”编译错误。我想这与接口(interface)有关。
我的意思是对于接口(interface)来说,情况更加困难。例如:
interface SomeInterface {}
class SomeClass {}
SomeClass someObject = new SomeClass();
SomeInterface someInterface = (SomeInterface)someObject;
throws ClassCastException
认为在编译时很清楚,SomeClass
对象不能转换为 SomeInterface
。
最佳答案
接口(interface)没必要。强制转换告诉编译器您将从另一种类型的变量引用一种类型的实例。
当强制转换建议的类型转换不可行时,您会收到编译错误。
即String s = (String) new Integer(1);
有时可以,有时不可以,代码会编译,但您可能会得到 ClassCastException。
即
Object o = ...;
String s = (String) o;//Depending on the content of o, this line may throw a ClassCastException
关于java - ClassCastException 与 "inconvertible types"编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21864402/