java.lang.ClassCastException 在运行时或编译时

java.lang.ClassCastException at runtime or compile-time

我刚刚在一本 OCA 书籍(Oracle 认证助理)中读到:

"Some casts exceptions can be detected as errors at compile-time, but others can only be detected at runtime".

现在我试图为这两种情况找到一个例子:编译时和运行时间。

考虑以下 class 结构:

class A {}

class B extends A {}

class C extends B {}

以下演员表

Object o = new C();
B b = (B) o;

是正确的。所以代码将 运行 没有 ClassCastException.

演员阵容

Object o = new B();
C c = (C) o;

错了。对象 o 至少是 B 类型;所以它可以转换为 BA.

但是这可以在 运行 时或编译时检测到吗? 我会在编译时猜测?!还是编译器只知道引用的类型,而不知道对象(在内存中)本身的类型?如果这是真的,编译器无法在编译时决定转换是否正确。

感谢您的帮助!

Or does the compiler knows only the type of the reference, not of the object (in the memory) itselfs?

它只知道您要投射的表达式的类型。该表达式的类型为 Object,因此就编译器而言,可以将其转换为 C。虽然语言 could 的设计目的是让这个错误在编译时被发现,但要确定编译器必须推断的内容和不能推断的内容的精确语义是很困难的...而且您真的不想要 some 编译器允许而 some 不允许的代码。

虽然这会在编译时失败:

String s = "";
C c = (C) s; // Can't possibly be true