从对象转换为布尔有效 Java 语言吗?

Is casting from Object to boolean valid Java language?

我在工作中偶然发现了一个 C 程序员多年前实现的旧 Java 代码,我们忍不住开始讨论代码是否存在 - 即使它编译和有效 - 实际上是有效的 Java 代码。

final Object o = Boolean.TRUE;
boolean b = (boolean) o;

这实际上是有问题的代码。正如您所看到的,从对象到原始布尔值的转换不太好,这不应该是可能的,但由于一些隐含的拳击魔法,它恰好起作用了。

如果我执行以下操作

final Object o = Boolean.TRUE;
if (o instanceof Boolean) {
  b = (boolean) o;
}

我什至在 o 被强制转换为 b 的那一行收到警告说 "Cast is incompatible with given instanceof"。这显然是正确的,但由于隐式装箱仍然有效。

现在的问题是:Java 规范是否真的允许强制转换,因此应该适用于未来的 JVM 版本?或者它只是碰巧在当前版本中工作,可能在未来的 JVM 更新中不再工作?

是的。这是合法的。请参阅 JLS-5.1.8. Unboxing Conversion 其中(部分)

Unboxing conversion converts expressions of reference type to corresponding expressions of primitive type. Specifically, the following eight conversions are called the unboxing conversions:

  • From type Boolean to type boolean

这在 JLS 8, section 5.5 中定义。它特别允许通过从 Object 到原始类型的拆箱转换进行转换(另请参见 table 5.5-A)。具体来说,JLS 说:

An expression of a reference type may undergo casting conversion to a primitive type without error, by unboxing conversion.

有关更多详细信息,请参阅我对类似问题的回答:Differences in auto-unboxing between Java 6 vs Java 7