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?
BeginnerAnswer
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.