This article refers to the difference between class.forname () and Classloader.loadclass () in the reflection Java class loading process
Load: Locate the. class file and load the byte code contained in this file into memory
Links: Performs the following validation, preparation, and parsing steps, where parsing steps are optional;
checksum: Checking the correctness of binary data for imported classes or interfaces (file format verification, metadata validation, bytecode verification, symbolic reference validation)
Preparation: Assigns and initializes the storage space to the static variables of the class;
Initialization: Activates the initialization Java code and static Java code blocks of static variables for the class, and initializes the variable values that the programmer sets.
Class.forName (ClassName) method, the method that is actually called internally is
Class.forName (Classname,true,classloader);
The 2nd Boolean parameter indicates whether the class needs to be initialized, and Class.forName (ClassName) is required to initialize by default.
Once initialized, the static block code execution of the target object is triggered, and the static parameter is initialized again.
Classloader.loadclass (ClassName) method, the method that is actually called internally is
Classloader.loadclass (Classname,false);
The 2nd Boolean parameter, which indicates whether the target object is linked, false means no link, as described above,
Without linking means that some column steps, including initialization, are not performed, then static blocks and static objects are not executed.
A class that contains a static block
Package Com.yvan.reflex;
public class User {
private String username;
static{
System.out.println ("This is the static block");
}
Public String GetUserName () {return
username;
}
public void Setusername (String username) {
this.username = username;
}
@Override public
String toString () {return
"User [username=" + username + "]";
}
}
Class.forName (), the static block is loaded
String className = User.class.getName ();
System.out.println (className);
Default initialization static module
class<?> object = Class.forName (ClassName);
Print results
Com.yvan.reflex.User this are
static block
Classloader.loadclass () way
public class Appmain {public
static void Main (string[] args) throws Exception {
String className = User.class.get Name ();
System.out.println (className);
Process P = new process ();
P.init (ClassName);
}
Class Process {public
void init (String className) throws ClassNotFoundException, Instantiationexception, illegalaccessexception {
//does not initialize the static module
class<?> object = This.getclass (). getClassLoader (). LoadClass (className);
Object obj = object.newinstance ();
}
}
Print results
Com.yvan.reflex.User