Learn object initialization order through Java bytecode analysis

  • 2020-04-01 02:32:09
  • OfStack


mockery.checking(new Expectations() {

           {
               one(new Object()).toString();
               will(returnValue(""));
           }
       });

Let's write a simple class to illustrate this example


public class Test {

    int i = 1;
    {
        int j = 1;
        System.out.println(j);
    }
public Test(){
i = 2;
}
static{
}
}

Previously has been using static{} code fast, the original can directly write {} code block

Through the analysis of Java bytecode, it is found that the execution order of the code is as follows:

1 first executes the constructor method for the object, creates an empty object, and then assigns the default value to the object's field I. So I equals zero first.

2 and then assign the fields in turn, so in our example, there's only one field I, so I = 1, and that's the field initialization

The {} statement blocks of the class are executed after the 4 fields are initialized, and if there are multiple {} statement blocks, they are executed in code order

When the 3 {} statement is completed, constructor method I = 2 is executed


Related articles: