What code does the compiler generate for autoboxing?

后端 未结 4 1454
梦如初夏
梦如初夏 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:37

    I came up with a unit test that proves that Integer.valueOf() is called instead of the wrapper's constructor.

    import static org.junit.Assert.assertNotSame;
    import static org.junit.Assert.assertSame;
    
    import org.junit.Test;
    
    public class Boxing {
        @Test
        public void boxing() {
            assertSame(5, 5);
            assertNotSame(1000, 1000);
        }
    }
    

提交回复
热议问题