

You can also call the Class.forName(String name, boolean initialize, ClassLoader loader) method to manually select whether to initialize the class when loading the class. The source code of Class.forName(String name, boolean initialize, ClassLoader loader) is as follows: /* name fully qualified name of the desired class The last method called is the forName0 method.The second parameter in the forName0 method is set to true by default.This parameter represents whether to initialize the loaded class.When set to true, the class will be initialized, which means that the class will be executed.The static code block, as well as the assignment of static variables and other operations. Return forName0(className, true, ClassLoader.getClassLoader(caller), caller) The Class.forName() method is actually implemented by the called CLassLoader.Ĭlass.forName(String className) the source code of this method is static Class forName(String className)Ĭlass caller = Reflection.getCallerClass() The function implemented is to "get a binary byte stream describing this class through the fully qualified name of a class", and then place the binary stream in the JVM after obtaining the binary stream. ClassLoader is the class loader that finally calls the startup class loader following the parental delegation model. explainīoth Class.forName() and ClassLoader can load classes in java. Recently, I was asked in the interview process, the difference between Class.forName() loading class and using ClassLoader to load class in Java reflection. I didn't think of it at the time, and then I researched it and wrote it down.
