Java order of Initialization and Instantiation

前端 未结 2 2229
说谎
说谎 2020-11-22 06:32

I am trying to piece together the process of Initialization and Instantiation in the JVM but the JLS is a little obtuse on a few details, so if anyone would mind clearing up

2条回答
  •  离开以前
    2020-11-22 07:18

    Following is an example that print the order of each step during object creation.

    InstanceCreateStepTest.java:

    import javax.annotation.PostConstruct;
    
    /**
     * Test steps of instance creation.
     * 
     * @author eric
     * @date Jan 7, 2018 3:31:12 AM
     */
    public class InstanceCreateStepTest {
        public static void main(String[] args) {
            new Sub().hello();
            System.out.printf("%s\n", "------------");
            new Sub().hello();
        }
    }
    
    class Base {
        static {
            System.out.printf("%s - %s - %s\n", "base", "static", "block");
        }
        {
            System.out.printf("%s - %s - %s\n", "base", "instance", "block");
        }
    
        public Base() {
            System.out.printf("%s - %s\n", "base", "constructor");
        }
    
        @PostConstruct
        public void init() {
            System.out.printf("%s - %s\n", "base", "PostConstruct");
        }
    
        public void hello() {
            System.out.printf("%s - %s\n", "base", "method");
        }
    }
    
    class Sub extends Base {
        static {
            System.out.printf("%s - %s - %s\n", "sub", "static", "block");
        }
        {
            System.out.printf("%s - %s - %s\n", "sub", "instance", "block");
        }
    
        public Sub() {
            System.out.printf("%s - %s\n", "sub", "constructor");
        }
    
        @PostConstruct
        public void init() {
            System.out.printf("%s - %s\n", "sub", "PostConstruct");
        }
    
        @Override
        public void hello() {
            // super.hello();
            System.out.printf("%s - %s\n", "sub", "method");
        }
    }
    

    Execution:

    Just invoke the main method, and then check the output.

    Tips:

    • The methods marked by @PostConstruct won't be invoked, unless you invoke it inside some container, like Spring-boot, since it depends on those containers to implement annotation like @PostConstruct.

提交回复
热议问题