Why dup command is required for constructing an object using java bytecode?

Source: Internet
Author: User

Java code
Package jvm. study;
 
Public class Test {
 
/**
* @ Param args
*/
Public static void main (String [] args ){
Test t = new Test ();
}
 
}


The bytecode generated by this Code is as follows:
Java code
// Compiled from Test. java (version 1.6: 50.0, super bit)
Public class jvm. study. Test {

// Method descriptor #6 () V
// Stack: 1, Locals: 1
Public Test ();
0 aload_0 [this]
1 invokespecial java. lang. Object () [8]
4 return
Line numbers:
[Pc: 0, line: 3]
Local variable table:
[Pc: 0, pc: 5] local: this index: 0 type: jvm. study. Test

// Method descriptor #15 ([Ljava/lang/String;) V
// Stack: 2, Locals: 2
Public static void main (java. lang. String [] args );
0 new jvm. study. Test [1]
3 dup
4 invokespecial jvm. study. Test () [16]
7 astore_1 [t]
8 return
Line numbers:
[Pc: 0, line: 9]
[Pc: 8, line: 10]
Local variable table:
[Pc: 0, pc: 9] local: args index: 0 type: java. lang. String []
[Pc: 8, pc: 9] local: t index: 1 type: jvm. study. Test
}

Here we can see that the main method is mainly used
Java code
0 new jvm. study. Test [1]
3 dup
4 invokespecial jvm. study. Test () [16]
7 astore_1 [t]
8 return

Here is a dup command. The function is to copy the reference of the previously allocated jvm. study. Test space and press it to the top of the stack. So why do we need to do this? Because the invokespecial Command finds the jvm. study. Test () constructor through the [16] constant pool entry, although the constructor finds the constructor. However, you must know who the constructor is. Therefore, you must push the application of the previously allocated space to the top of the stack and let the invokespecial command application know that the original constructor is the reference just created, after the call is complete, the value at the top of the stack is displayed.
Then, call astore_1 to save the top value of the stack to a local variable.

Author "Code life"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.