编译器为自动装箱生成了什么代码? [英] What code does the compiler generate for autoboxing?
本文介绍了编译器为自动装箱生成了什么代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当Java编译器将一个原语自动装箱到包装类时,它会在幕后生成什么代码?我想它会调用:
When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:
- 包装器上的valueOf()方法
- 包装器的构造函数
- 其他一些魔法?
推荐答案
你可以使用 javap
工具可供您自己查看。编译以下代码:
You can use the javap
tool to see for yourself. Compile the following code:
public class AutoboxingTest
{
public static void main(String []args)
{
Integer a = 3;
int b = a;
}
}
编译和反汇编:
javac AutoboxingTest.java
javap -c AutoboxingTest
输出为:
Compiled from "AutoboxingTest.java"
public class AutoboxingTest extends java.lang.Object{
public AutoboxingTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_3
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_1
5: aload_1
6: invokevirtual #3; //Method java/lang/Integer.intValue:()I
9: istore_2
10: return
}
因此,正如您所看到的,自动装箱调用静态方法 Integer.valueOf()
,并且自动装箱调用给定的 Integer
对象上的 intValue()
。没有别的,真的 - 它只是语法糖。
Thus, as you can see, autoboxing invokes the static method Integer.valueOf()
, and autounboxing invokes intValue()
on the given Integer
object. There's nothing else, really - it's just syntactic sugar.
这篇关于编译器为自动装箱生成了什么代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文