What code does the compiler generate for autoboxing?

后端 未结 4 1455
梦如初夏
梦如初夏 2020-11-27 20:37

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 t
4条回答
  •  感动是毒
    2020-11-27 21:21

    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;
        }
    }
    

    To compile and disassemble:

    javac AutoboxingTest.java
    javap -c AutoboxingTest
    

    The output is:

    Compiled from "AutoboxingTest.java"
    public class AutoboxingTest extends java.lang.Object{
    public AutoboxingTest();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."":()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
    
    }
    

    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.

提交回复
热议问题