Using Class.forName() for Dynamic Loading
What you'll learn: How to load Java classes at runtime using their fully qualified name as a string, enabling flexible and dynamic class resolution.
The Core Idea
Class.forName() allows you to load a class when you only know its name as a String at runtime, rather than at compile time. This is incredibly powerful for scenarios where the exact class you need isn't determined until your program is running—like loading database drivers, plugin systems, or configuration-driven applications.
Think of it like ordering food by telling the waiter the dish's name rather than pointing at a menu item. You're using a text description to dynamically retrieve what you need.
The Syntax
Class<?> clazz = Class.forName("java.util.ArrayList");
This loads the ArrayList class by its fully qualified name. The method returns a Class object representing that type.
Why It Matters
Unlike .class literals or getClass(), which require you to reference the class directly in your code, Class.forName() accepts a String. This means:
- The class name can come from configuration files
- It can be user input (with appropriate validation)
- Different classes can be loaded based on runtime conditions
String className = readFromConfig(); // might return "com.example.MyPlugin"
Class<?> dynamicClass = Class.forName(className);
Important Notes
- The string must be the fully qualified name (package + class name)
- If the class isn't found,
ClassNotFoundExceptionis thrown (checked exception) - The class is initialized (static blocks run) when loaded this way
Key Takeaway: Class.forName() enables dynamic class loading by accepting a class name as a String, making your code adaptable to runtime conditions and external configuration.