All 15 Class Loading & Bytecode Verification questions
More in Class Loading & Bytecode Verification
Advertisement
Back to results for “Reflection API”
Java › Class Loading & Bytecode Verification

How do you programmatically load a class by its fully-qualified name at runtime using Class.forName(), and what is a common real-world use case for this?

Beginner

Answer

Class.forName(String className) locates, loads, links, and (by default) initializes the named class, returning its Class object -- commonly used to register a JDBC driver dynamically (older JDBC driver versions required this call to trigger their static initializer, which registers the driver with DriverManager), or in plugin architectures where the specific implementation class name is only known at runtime, such as from a configuration file.
try {
    Class.forName("com.mysql.cj.jdbc.Driver");  // triggers the driver's static initializer
    Connection conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
    throw new RuntimeException("MySQL driver not found on classpath", e);
}
Real-world example A plugin system reads a fully-qualified class name from a configuration file at startup, then uses Class.forName() combined with reflection to instantiate the correct plugin implementation dynamically, without the core application needing any compile-time reference to specific plugin classes.

Common follow-ups: Is Class.forName() still necessary for modern JDBC drivers using the ServiceLoader mechanism (JDBC 4.0+)?;What's the difference between Class.forName(name) and Class.forName(name, false, loader)?