Java 8 : Merge String[] and int[] into Object[] when verifying bytecode

标签 java jvm bytecode jvm-bytecode

我正在阅读 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/

相关文章:

java - 我如何为在 MySQL 数据库中保存自身实例的 Java 对象建模?

java - 模拟汽车(Java)

java - 有没有办法将 GC 限制在 JVM 中仅占用 CPU 的特定百分比?

java - ASM : how to easily get proper Opcode based on type

java - ASM字节码: prepending visitMethodInsn with another invocation

java - 泛型类型参数依赖于自身

java - 如何从类对象中查找源代码语言?

Java:输入/使用 "try-catch" block 的开销?

java - 适用于每个 JVM 的最小 Java 类文件是什么?

java - 是否有类似的 VisitLdcInsn 用于加载对象(不是常量)?