为什么 javac 对数组进行两次检查?
检查字节码,我注意到 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 javac 的已知错误。但它大多是无害的。
It is a known bug of javac. But it is mostly harmless.