Class loading
When a class is loaded by the loader
2. Call a static variable or method in a class.Copy the code
The type of the class loader
1. BootstrapClassLoader 2. ExtClassLoader 3. System loader AppClassLoaderCopy the code
Class loading process
loading
- ClassLoader finds this by the fully qualified name of a class (package name + class name)
.class
File and generate a binary byte stream.Note: Bytecode sources can be. Class files, JAR packages, ZIP packages, byte streams from the network.
- will
.class
Each part of the file is parsed into a specific data structure within the JVM and stored in a method area. - Create one in memory
java.lang.Class
Object of type.Note: All access to this class is through this class object during program execution
.
When does the JVM reprint a.class file?
- Implicit loading: When an object is generated using methods such as New, the system implicitly calls a ClassLoader to load the corresponding class into memory.
- Display loading: when using reflection methods such as class.forname ().
link
validation
To ensure that the byte stream of the. Class file contains information that meets the requirements of the current virtual machine and does not compromise the security of the virtual machine itself.
- File format verification: Verifies that the file byte stream complies with the. Class file format specification and can be processed by the current version of the VM.
- Metadata validation: Semantic analysis of the information described by bytecode to ensure that what is described conforms to the Requirements of the Java language specification.
- Bytecode verification: Through data flow and control flow analysis to determine that program semantics are legitimate and logical.
- Symbolic reference checking: Verifies the match of information outside the class itself (various symbolic references in the constant pool).
To prepare
Allocate memory for static variables in a class and set a “0 value “for them (default)
- The default value for basic types (int, long, short, byte, char, Boolean, float, double) is 0,
- The default value for reference type is NULL.
Note: If it is a static constant, it is assigned to a constant value directly after memory is allocated during the preparation phase.
parsing
Convert symbolic references in the constant pool to direct references, that is, concrete memory addresses.
-
The analogy between symbolic reference and direct reference
For example, when chatting on wechat, the name or alias of the friend is saved in the wechat friend list, which can be regarded as symbolic reference. When we send a message to a friend, we will find the IP address of the friend based on the friend’s name, which can be regarded as a direct reference.
Initialize the
The process of executing the <cinit> method of the class constructor and actually initializing the class variable by assigning a true value to the static variable that was assigned a "zero value" during the preparation phase.
Initialization time?
- Unsolicited quotation:
- When the virtual machine starts, initialize the main class that contains the main method.
- When the new directive creates an object instance, it initializes the object if the target object has not been initialized.
- When an instruction is encountered that accesses a static method or field, initialize if the target object has not been initialized.
- Initialization of a subclass If its parent class is not initialized, the initialization of its parent class must be triggered first.
- With reflection, initialize if the target object has not been initialized.
- The first call to Java. Lang. Invoke. MethodHandle instance, need to initialize MethodHandle point method in the class.
Initialize class variables
During the initialization phase, only static assignment statements associated with the class and static statements, that is, information modified by the static keyword, are initialized. Blocks without static modifications are executed when the object is instantiated.
Passive reference
A passive reference does not initiate class initialization.
Calls a static variable of the parent class in a subclass.
Only classes that directly define this field are initialized. Using a subclass to refer to a static field defined in a parent class triggers the initialization of the parent class but not the subclass.
Class object initialization and object creation order
When using new to create an instance object of a class, the order of execution between static code blocks, non-static code blocks, and constructors in the class. Static variables/static code blocks – > non-static code blocks – > constructors
- Superclass static variables and static code blocks
- Subclass static variables and static code blocks
- Parent class non-static member variables and non-static code blocks
- Constructor of the parent class
- Nonstatic member variables and nonstatic code blocks of subclasses
- The constructor of a subclass
Class loading mechanism (parental delegation)
When a class loader receives a request to load a class or resource, it usually delegates the request to the parent class loader. Only when the parent class loader cannot find the specified class or resource, the parent class loader performs the actual loading process.
ClassLoader#loadClass
protectedClass<? > loadClass(String name,boolean resolve) throws ClassNotFoundException { synchronized (getClassLoadingLock(name)) { // First, check if the class has already been loadedClass<? > c = findLoadedClass(name);if (c == null) { long t0 = System.nanoTime(); try { if(parent ! =null) { c = parent.loadClass(name, false); } else{ c = findBootstrapClassOrNull(name); }}catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. long t1 = System.nanoTime(); c = findClass(name); // this is the defining class loader; record the statssun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); sun.misc.PerfCounter.getFindClasses().increment(); }}if (resolve) { resolveClass(c); } returnc; }} ` ` `Copy the code
- It first checks whether the Class is loaded and returns it if it is.
- If the Class has not been loaded, the parent Class loader is determined to be null. If not, the parent Class loader is assigned the loading task.
- If it is empty, the loading task is handed over to the boot class loader.
- If neither the parent class loader nor the start class loader has loaded successfully, the current class’s
findClass
Method continues trying to load.
Custom class loaders
- inheritance
ClassLoader
. - rewrite
findClass
Methods. - call
defineClass
Converts bytecode to a Class object and returns it.