ClassLoaderAndClass.forName
ClassLoaderAndClass.forName
loadClass()
The primary difference between Class.forName() and ClassLoader.loadClass() lies in the way they load classes and
initialize them. Below is a detailed comparison:
1. Class.forName(String className)
Purpose: Loads and initializes a class.
Initialization: This method not only loads the class but also initializes it (executes static blocks and initializes
static variables).
Example:
Class<?> clazz = Class.forName("com.example.MyClass");
eg:
The class com.example.MyClass will be loaded.
If the class contains a static block or static fields, they will be executed or initialized.
Use Case: When you need the class to be initialized immediately after being loaded.
eg, in JDBC, it is used to load and initialize the driver class:
Class.forName("com.mysql.cj.jdbc.Driver");
2. ClassLoader.loadClass(String className)
Purpose: Loads a class but does not initialize it.
Initialization: The class is loaded into memory, but its static blocks and static variables are not executed or
initialized until the class is explicitly used (e.g., by accessing a static method or field).
Example:
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class<?> clazz = classLoader.loadClass("com.example.MyClass");
eg:
The class com.example.MyClass will be loaded, but static blocks and variables will not be executed or
initialized until explicitly referenced.
Use Case: When you want to delay the initialization of the class or just load the class metadata for
introspection.
Key Differences
Feature Class.forName() ClassLoader.loadClass()
Initialization Loads and initializes the class Loads the class but does not initialize it
Execution of static Executes static blocks and initializes
Does not execute static code
code static variables
When immediate initialization is When lazy initialization is required or only
Use Case
needed loading is needed
Exception Handling Throws ClassNotFoundException Throws ClassNotFoundException
Summary
Use Class.forName() when you need the class to be initialized upon loading.
Use ClassLoader.loadClass() when you just want to load the class and delay initialization.