Monday, June 22, 2009

How Class.forName() registers driver?

Most of the time for registering driver to DriverManager, we use the following code.

Class.forName("com.mysql.jdbc.Driver");

But Class.forName() method will not do any registration of Driver with DriverManager. If that is the case how DriverManager.registerDriver() (registration) is called?

static {

try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (java.sql.SQLException E) {
throw new RuntimeException("Can't register driver!");
}

}

This is snippet is taken from com.mysql.jdbc.Driver class's source code. So if you closely watch this code, when ever
 Class.forName("com.mysql.jdbc.Driver");
is invoked as soon as the class is loaded in to the memory, all static blocks of that classes are also being invoked. Insite one of the static block all driver classes are registering them self to DriverManager.

No comments: