Learn how to use the Class.forName() method in Java with syntax, examples, output, advantages, and real-world use cases for dynamic class loading.
The Class.forName() method in Java is used to load a class dynamically at runtime. It is commonly used in JDBC applications, frameworks, reflection APIs, and plugin-based systems. This method returns the Class object associated with the specified class name without creating an instance of that class.
Code Explanation (Step-by-Step)
- forName(“java.lang.ClassLoader”) loads the ClassLoader class.
- getName() returns the fully qualified class name.
- forName(“java.lang.String”) loads the String class.
- toString() returns class java.lang.String.
- Class<?> is preferred over raw Class because it provides type safety.
- It is commonly used in Reflection API, JDBC driver loading, and dynamic class loading.
public class AppMain {
public static void main(String[] args) {
try {
Class> cname = Class.forName("java.lang.ClassLoader");
System.out.println("Name of Class :- " + cname.getName());
Class> ctype = Class.forName("java.lang.String");
System.out.println("Class type represented as :- " + ctype);
} catch (ClassNotFoundException ex) {
System.out.println(ex);
}
}
}
Output :-
Name of Class :- java.lang.ClassLoader
Class type represented as :- class java.lang.String
Advantages of Class.forName()
- Supports Dynamic Class Loading by loading classes at runtime using their fully qualified class names.
- No Object Creation Required, as it returns the Class object without creating an instance of the class.
- Useful for Reflection API operations such as inspecting class metadata, methods, fields, and constructors.
- Reduces Compile-Time Dependencies because class names can be specified dynamically as strings.
- Widely Used in JDBC for loading database driver classes dynamically.
- Returns Class Metadata through the Class object, enabling runtime analysis of classes.
- Improves Reusability by allowing the same code to work with different classes dynamically.
- Commonly Used in Enterprise Frameworks such as Spring, Hibernate, and other reflection-based frameworks.