When Does Class.forName Initialize a Class? Java Class Loading Explained
This article explains the difference between Java's Class.forName and ClassLoader when loading classes, shows how the initialize flag controls static initialization, provides code examples, and discusses practical scenarios such as Spring IoC and JDBC driver registration.
Preface
During a recent interview I was asked about the difference between Class.forName() and using a ClassLoader to load a class in Java. I later researched and documented the findings.
Explanation
In Java both Class.forName() and ClassLoader can load classes. Class.forName() internally invokes a ClassLoader. The method ultimately calls forName0, whose second parameter is true by default, meaning the class is initialized (static blocks, static fields, etc.) during loading.
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}The overloaded version allows explicit control of initialization:
/* @param name fully qualified name of the desired class
* @param initialize if true the class will be initialized.
* @param loader class loader from which the class must be loaded */
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException {
Class<?> caller = null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Reflective call to get caller class is only needed if a security manager is present.
caller = Reflection.getCallerClass();
if (sun.misc.VM.isSystemDomainLoader(loader)) {
ClassLoader ccl = ClassLoader.getClassLoader(caller);
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
return forName0(name, initialize, loader, caller);
}The comment in the source code states that if the initialize parameter is true, the class will be initialized.
Example
Consider a class that contains a static block, a static field, and a static method that assigns the field:
public class ClassForName {
// static block
static {
System.out.println("Executed static block");
}
// static field
private static String staticField = staticMethod();
// static method that assigns the static field
public static String staticMethod() {
System.out.println("Executed static method");
return "Assigned to static field";
}
}Test method using Class.forName():
@Test
public void test45() {
try {
ClassLoader.getSystemClassLoader().loadClass("com.eurekaclient2.client2.ClassForName");
System.out.println("#########-------------End##########");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}Result:
Executed static block
Executed static method
#########-------------End##########Test method using ClassLoader.loadClass() produces only the end marker, showing that the class is loaded but not initialized.
#########-------------End##########Thus, Class.forName triggers class initialization, while ClassLoader.loadClass does not.
Application Scenarios
Spring’s IoC container uses ClassLoader to load classes. In JDBC, the driver class must register itself with DriverManager, which is typically done in a static block. Therefore, the driver is loaded with Class.forName() to ensure the static registration code runs.
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// static fields/initializers
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException e) {
throw new RuntimeException("Can't register driver!");
}
}
// constructors and other methods...
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
