Function of Class. forName () and function of class. forname
We all use Class. forName () and all know it is the function of Class loading. In fact, this method is not just Class loading, but also Class initialization.
The following is a small example:
Class A is the class used for loading.
/*** The class used to test the class loading has * static code block, static parameter * code block, parameter * constructor */public class A {static int I = 1; static {System. out. println ("static code block initialization");} int x = 0; {System. out. println ("code block initialization");} public A () {System. out. println ("constructor initialization ");}}
TestClass, used to test the test class of the loading class:
/*** This method is used to test the Class. forName () function */public class TestClass {/*** Class. the forName () method does two things * 1. will load the specified class to the memory * 2. then initialize the specified class (class initialization only initializes static parameters and code blocks, because the static is the same as the class) * @ throws ClassNotFoundException */@ Test public void test () throws ClassNotFoundException {Class clazz = Class. forName ("A");}/*** Class. forName (String clazz, boolean bl, ClassLoader cl) * The first parameter is the class path for loading the class * The second parameter can specify whether to initialize the class during class loading * The third parameter can specify the Class Loader for loading the class * @ throws ClassNotFoundException * // @ Test public void test2 () throws ClassNotFoundException {ClassLoader cl = Class. forName ("TestClass "). getClassLoader (); Class. forName ("A", true, cl );}}
Result:
1. The output result of test () is
Static code block Initialization
Note: Class. forName () not only loads classes, but also initializes Class parameters (static ).
2. The output result of test2 () is
(Null)
Description: Class. forName (String, boolean, ClassLoader) can specify the Class path for loading the Class, whether to initialize Class parameters, and the Class loader for loading the Class. When the second parameter is false, only the class is loaded and the class is not initialized.
In fact, after analyzing the source code of Class. forName (), we will find that the forName (String) method and forName (String, true, currentClassloader) have the same effect!