编译器为自动装箱生成什么代码?
当 Java 编译器自动将原语装箱到包装类时,它会在幕后生成什么代码? 我想象它调用:
- 包装器上的 valueOf() 方法
- 包装器的构造函数
- 还有其他魔法吗?
When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:
- The valueOf() method on the wrapper
- The wrapper's constructor
- Some other magic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
javap
工具亲自查看。 编译以下代码:编译和反汇编:
输出为:
因此,如您所见,自动装箱调用静态方法
Integer.valueOf()
,自动拆箱调用intValue()
code> 给定的 Integer 对象。 真的没有别的了——这只是语法糖。You can use the
javap
tool to see for yourself. Compile the following code:To compile and disassemble:
The output is:
Thus, as you can see, autoboxing invokes the static method
Integer.valueOf()
, and autounboxing invokesintValue()
on the givenInteger
object. There's nothing else, really - it's just syntactic sugar.我想出了一个单元测试来证明调用了 Integer.valueOf() 而不是包装器的构造函数。
I came up with a unit test that proves that Integer.valueOf() is called instead of the wrapper's constructor.
如果您查找 API 文档 Integer#valueOf(int),你会看到它是在 JDK 1.5 中添加的。 所有包装器类型(尚未拥有它们)都添加了类似的方法来支持自动装箱。 对于某些类型,还有附加要求,如 JLS 中所述:
值得注意的是尽管
-128..127
范围内的 Long 值像其他整数类型一样缓存在 Sun 的实现中,但long
不受相同要求的约束。我还刚刚在我的 Java 编程的副本中发现Language,它说从
\u0000
到\u00ff
的char
值被缓存,但当然每个规范的上限是\u007f
(Sun JDK 符合本例中的规范)。If you look up the API doc for Integer#valueOf(int), you'll see it was added in JDK 1.5. All the wrapper types (that didn't already have them) had similar methods added to support autoboxing. For certain types there is an additional requirement, as described in the JLS:
It's interesting to note that
long
s aren't subject to the same requirement, although Long values in the-128..127
range are cached in Sun's implementation, just like the other integral types.I also just discovered that in my copy of The Java Programming Language, it says
char
values from\u0000
to\u00ff
are cached, but of course the upper limit per the spec is\u007f
(and the Sun JDK conforms to the spec in this case).我建议使用 jad 之类的东西并大量反编译代码。 您可以了解很多有关 java 实际用途的信息。
I'd recommend getting something like jad and decompiling code a lot. You can learn quite a bit about what java's actually doing.