The difference between LoadClass and forName

LOACF
One, Java class loading process
Insert picture description here

Loading: Obtain the binary byte stream through the tired fully qualified name, convert the binary byte stream into the runtime data structure in the method area, and generate the Java.lang.class object in the memory;

Link: Perform the following verification, preparation and analysis steps, of which the analysis step is optional;

Verification: Check the correctness of the binary data of the imported class or interface; (file format verification, metadata verification, bytecode verification, symbol reference verification)

Preparation: Allocate and initialize storage space for static variables of the class;

Analysis: Convert symbol references in the constant pool into direct references;

Initialization: Activate the initialization Java code and static Java code block of the static variable of the class, and initialize the variable value set by the programmer.

Two, analyze Class.forName () and ClassLoader.loadClass

Class.forName(className) method, the method actually called inside is Class.forName(className,true,classloader);

The second boolean parameter indicates whether the class needs to be initialized. Class.forName(className) needs to be initialized by default.

Once initialized, it will trigger the execution of the static block code of the target object, and the static parameters will also be initialized again.

ClassLoader.loadClass(className) method, the method actually called internally is ClassLoader.loadClass(className,false);

The second boolean parameter indicates whether the target object is linked or not, false means that the link is not to be performed. It is possible from the above description. Not linking means that a series of steps including initialization are not performed, then the static block and static object will not be executed

In addition to loading the .class file of the class into the JVM, class.forName() also interprets the class and executes the static block in the class.
The classLoader only does one thing, which is to load the .class file into the JVM, it will not execute the content in the static, and only execute the static block in the newInstance.
Class.forName(name, initialize, loader) function with parameters can also control whether to load static block. And only when the newInstance() method is called, the constructor is called to create the object of the class.

Guess you like

Origin blog.csdn.net/qq_32907195/article/details/112954119