This code is forcing the class representing the MySQL driver to load and initialize. In Java, a class is not loaded unless it is necessary that the class gets loaded. Since JDBC code usually never directly references the driver, it wouldn’t get loaded without Class.forName
(or some other equivalent alternatives).
Note that it is necessary to both load and initialize the class, which are 2 different things.
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
Also, note that it is not necessary to call .newInstance()
– the static initializer of the Driver already registers itself as a JDBC driver.
Finally, note that with the Service Loader API it is usually not necessary to call Class.forName() to load the driver: it can be loaded automatically.
