The process of using a certain type of Java virtual machine can be divided into seven stages:
Load-verify-prepare-Parse-Initialize-use-uninstall
This article only describes the conditions under which class initialization is performed.
The Java virtual machine specification strictly regulates when class initialization is performed. There are only four scenarios:
1. Master class specified when the VM is started.
Class that contains the main method.
2. When there are four commands, new, getstatic, putstatic, and invokestatic.
New: use the new keyword to instantiate an object.
Getstatic: Read the static fields of a class.
Putstatic: Write static fields that reference a class.
Invokestatic: Call the static method of a class.
3. When initializing a class, initialize its parent class first.
Interface is not. Initialization is performed only when the parent interface is actually referenced.
4. During class reflection calling.
Test code:
Mainclass:
Package COM. xuefeng. JVM. load;/*** initialization class time * 1. master class specified during VM startup * 2. when a new type of object is used, when a type of static variable is referenced, when a type of variable is set, and when a type of static method is called * 3. when initializing a class, initialize its parent class first. The parent interface is initialized only when the parent interface is actually used. * 4. when calling a class through reflection * @ author Xuefeng **/public class mainclass {static {system. out. println ("mainclass init. ");} // 1 public static void main (string [] ARGs) throws classnotfoundexception {// 2 // system. out. println ("superclass. f_v1: "+ superclass. f_v1); // system. out. println ("superclass. v1: "+ superclass. v1); // 3 // subclass S1 = new subclass (); // 3.1 If the static variable of the parent class is referenced by the subclass name, will the initialization of the subclass be triggered? // Depending on the specific Virtual Machine implementation, Sun hotspot virtual machine does not trigger subclass initialization at this time. System. Out. println (subclass. V1); // 4class. forname ("com. Xuefeng. JVM. Load. Subclass ");}}
Superclass:
Package COM. xuefeng. JVM. load; public class superclass {static {system. out. println ("superclass init. ");}/*** When referencing V1, superclass */public static int V1 = 1 will be initialized;/*** When referencing f_v1, variables of superclass * Static final will not be initialized. They are already put in the constant pool of the compiler */public static final int f_v1 = 1 ;}
Subclass:
package com.xuefeng.jvm.load;/** * * @author xuefeng * */public class SubClass extends SuperClass {static {System.out.println("SubClass init.");}}