The class loading process is the responsibility of the JVM class loader subsystem, which consists of three steps:
1) Load: Find and load binary data of type into virtual machine
1.通过某些途径,产生一个代表该类型的二进制数据流2.解析二进制数据流为方法区的内部数据结构3.在堆中创建一个表示该类型的Class实例(装载步骤的最终产品)
Note: The Java Virtual Machine specification allows the class loader to cache the binary representation of a Java type, and to wait for the class to be actively used when it throws an exception to the Linkageerror subclass
2) Connection:
1.验证 确保导入的类格式正确 检查final类不能有子类,final方法不能被覆盖,常量池检查,字节码完整性检查...
Note: The Java Virtual Machine designer can decide how to validate the type in a timely manner. The Java Virtual Machine specification lists the exceptions that virtual machines can throw and the conditions under which they must be thrown
2.准备 为类变量分配内存,设置默认初始值3.解析 把类型中的符号引用转换为直接引用(也可能推迟到真正需要使用某个符号引用时再去解析它) 在类型的常量池中寻找类,接口,字段和方法的符号引用,把类型中的符号引用转换为直接引用
3) Initialize: Initialize the class variable to the correct initial value
1.如果类存在直接超类,且直接超类还没有初始化,则先初始化直接超类2.如果类存在一个类初始化方法(“<clinit>”,并不是所有的类都存在这个方法,如果一个类没有类变量也没有静态初始化语句,就没有该方法),就执行它所有的类变量初始化语句和类型的静态初始化器都被Java编译器收集在一起,放到一个特殊的方法(“<clinit>”)中,称为类初始化方法,此方法只能被Java虚拟机调用
All Java Virtual machine implementations must be initialized at the first active use of each class or interface. There are the following six kinds
1) When creating a new instance of a class, either execute the new instruction in the bytecode, or through ambiguous creation, reflection, cloning, or deserialization.
2) When a static method of a class is called (that is, the invokestatic instruction is executed in the byte code)
3) When a static field of a class or interface is used, or when the field is assigned a value (that is, the getstatic or putstatic instruction is executed in the bytecode, except for the static field that is final decorated, it is initialized to a compile-time constant expression)
4) When invoking some of the reflection methods of the Java API, such as methods in class classes or classes in a Java.lang.reflect package
5) When a subclass of a class was originally initialized (except for the interface)
6) A class that is indicated as the startup class (with the main method) when the virtual machine starts
In addition to the above six scenarios, all other ways of using Java types are passive and do not cause initialization of Java types
Java class loading process