Who invokes the class initializer method and when?

后端 未结 3 717
鱼传尺愫
鱼传尺愫 2021-02-08 05:11

I know that the new, dup, invokespecial and astore bytecode pattern will invoke the instance initializer meth

3条回答
  •  情歌与酒
    2021-02-08 06:04

    is a static method added by javac and called by JVM after class loading. We can see this method in class bytecode with bytecode outline tools. Note that is added only if a class needs static initilization, e.g

    public class Test1 {
        static int x  = 1; 
    
        public static void main(String[] args) throws Exception {
        }
    }
    
    public class Test2 {
        static final int x  = 1; 
    
        public static void main(String[] args) throws Exception {
        }
    }
    

    Test1 has because its field x needs to be initialized with 1; while Test2 has no method because its x is a constant.

    It's also interesting to note that Class.forName has boolen intialize param which determines if the class should be initialized after loading or not.

提交回复
热议问题