我正在阅读 JVM 版本 8 ( https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html) 规范的第 4.10.2.2 节如何验证字节码。在这种情况下,控制流中会发生什么,当堆栈现在包含一个插槽时,当来自一个源时带有 int[],当来自另一个源时带有 String[]。
我阅读了以下 JVM 版本 7 文档中没有的内容:
If corresponding values are both array reference types, then their dimensions are examined. If the array types have the same dimensions, then the merged value is a reference to an instance of an array type which is first common supertype of both array types. (If either or both of the array types has a primitive element type, then Object is used as the element type instead.)
...
Even int[] and String[] can be merged; the result is Object[], because Object is used instead of int when computing the first common supertype.
这对我来说没有任何意义,因为这意味着 int[] 可以转换为 Object[]。但是在 Java 中,原始类型的数组不能转换为 Object[]。
谁能解释一下这背后的基本原理?
最佳答案
我不确定为什么该语言会出现在规范中,但它没有描述 JVM 实际行为的方式(这是有道理的,因为正如您所指出的,所描述的行为是无稽之谈)。
您可以找到推理字节码 validator 源here , 自 2013 年以来一直没有改变。
作为一项额外的检查,我创建了一个测试文件,它合并了一个 int[] 和一个 String[],然后在结果中存储了一个 String。不出所料,我收到了验证错误(Java 版本 1.8.0_111)。
关于Java 8 : Merge String[] and int[] into Object[] when verifying bytecode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904268/