为什么 javac 对数组进行两次检查?

发布于 2024-08-24 07:04:34 字数 864 浏览 2 评论 0原文

检查字节码,我注意到 javac 在转换为数组类型时似乎重复了 checkcast 指令。

Cast.java:javac

    class Cast {
      void test(Object a) {
        Object[] b = (Object[]) a;
      }
    }

编译版本的 javap 反汇编

    void test(java.lang.Object);
      Code:
       0:   aload_1
       1:   checkcast   #2; //class "[Ljava/lang/Object;"
       4:   checkcast   #2; //class "[Ljava/lang/Object;"
       7:   astore_2
       8:   return

测试 jikes 显示预期的单次转换

    void test(java.lang.Object);
      Code:
       0:   aload_1
       1:   checkcast   #10; //class "[Ljava/lang/Object;"
       4:   astore_2
       5:   return

checkcast 如果该对象不能被视为请求的类型并且不执行任何操作,则应该引发异常,因此我不明白为什么将演员阵容加倍会有帮助。我还没有查看 JDK 源代码来了解它是如何生成的,以及这是否有助于解释原因(也许这是一个提示)。

Examining bytecode, I've noticed javac seems to duplicate checkcast instructions when casting to array types.

Cast.java:

    class Cast {
      void test(Object a) {
        Object[] b = (Object[]) a;
      }
    }

javap disassembly of the javac compiled version

    void test(java.lang.Object);
      Code:
       0:   aload_1
       1:   checkcast   #2; //class "[Ljava/lang/Object;"
       4:   checkcast   #2; //class "[Ljava/lang/Object;"
       7:   astore_2
       8:   return

Testing jikes shows the expected single cast

    void test(java.lang.Object);
      Code:
       0:   aload_1
       1:   checkcast   #10; //class "[Ljava/lang/Object;"
       4:   astore_2
       5:   return

checkcast is supposed to raise an exception if the object can't be treated as the requested type and otherwise does nothing, so I don't see why it might help to double the cast. I haven't looked at the JDK sources to see how it's produced, and if that helps explain the why (maybe it's meant as a hint).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

焚却相思 2024-08-31 07:04:34

这是 javac 的已知错误。但它大多是无害的。

It is a known bug of javac. But it is mostly harmless.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文