We have already seen what is the use of Class.forName in Java, now lets see why we use Class.forName in JDBC, lets take an example that we are trying to register MySql driver using Class.forName(“com.mysql.jdbc.Driver”). The JVM will try to execute the static block of the Driver class which look like below.
public class Driver extends NonRegisteringDriver implements java.sql.Driver { static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } public Driver() throws SQLException { // Required for Class.forName().newInstance() } }
Where we can see we have a static block inside which we are creating a “new Driver()” object and passing it to registerDriver() method of DriverManager class.
The registerDriver() method gets the driver object and registers all information about MySql driver via DriverInfo class. We will then finally add the DriverInfo object into the drivers vector.
public static synchronized void registerDriver(java.sql.Driver driver) throws SQLException { if (!initialized) { initialize(); } DriverInfo di = new DriverInfo(); di.driver = driver; di.driverClass = driver.getClass(); di.driverClassName = di.driverClass.getName(); drivers.addElement(di); println("registerDriver: " + di); }
The DriverInfo is a package-private support class which holds Driver object, driverClass and driverClassName
class DriverInfo { Driver driver; Class driverClass; String driverClassName; public String toString() { return ("driver[className=" + driverClassName + "," + driver + "]"); } }
You even can register the driver just by creating object for the Driver class like below
com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
This will also execute the static block and registers the driver but we will not be using the driver object anywhere after that which causes the problem of having extra memory allocation. Hence we go for Class.forName approach.
Leave a Reply