The class is loaded in three stages: Loading, linking, and initializing, which are defined in 12.2, 12.3, and 12.4 of the Java language specification respectively.
Class. forname (classname)
Actually, it calls class. forname (classname, true,
This. getclass (). getclassloader ()). Note that the second parameter indicates whether the class must be initialized after being loading.
Classloader. loadclass (classname) actually calls classloader. loadclass (name, false). The second parameter indicates whether the class is linked. The difference comes out. The class loaded by class. forname (classname) has been initialized, while the class loaded by classloader. loadclass (classname) has not been linked.
Generally, both methods have the same effect and can load classes. However, if Program Class. forname (name) is required if the class is initialized.
Example
For example, in JDBC programming, we often see this usage, class. forname ("com. MySQL. JDBC. Driver"), if it is replaced
Getclass (). getclassloader (). loadclass ("com. MySQL. JDBC. Driver.
Why? Open Com. MySQL. JDBC. Driver Source code Look,
//
// Register ourselves with the drivermanager
//
Static {
Try {
Java. SQL. drivermanager. registerdriver (New Driver ());
} Catch (sqlexception e ){
Throw new runtimeexception ("can't register driver! ");
}
}
Originally, the driver registers itself in the static block to Java. SQL. drivermanager. The static block is executed during class initialization. Therefore, you can only use class. forname (classname ).