I have used jdbc without knowing this.Class.forname("Driver name") loads the driver class.But what does actually mean that ? When I searched in java docs for java.lang.Class it says it returned a Class object of the class name passed to it.Anybody please tell me the working of Class.forname() in general.
Joined: Oct 13, 2011
Quoting the Class API:
Returns the Class object associated with the class or interface with the given string name.
This means that the method returns an object of the class you have tried to find (in your project) when you passed a string as the class name.
Java supports type reflection - getting information about all class definitions - at runtime, and Class.forName() is a way to access the class definition.
When it's called, JVM loads that class definition into memory, and executes its static initializer and any static field assignments.
In the context of a JDBC drivers, all JDBC driver classes do something special in their static initializers...
What they do is they register themselves with the DriverManager.
The DriverManager stores a list of all such registered JDBC driver classes, to realize a "chain of responsibility" pattern.
Later on, when DriverManager.getConnection(conn_url) is called, it iterates through its list of registered classes, creates an instance of each, and asks each one to examine the conn_url and return a Connection if it can handle that URL. The first one to return a valid Connection becomes the driver for that URL.
The Class.forName() is not really required anymore since JDBC 4, because it brought in a driver discovery mechanism. Read DriverManager javadoc for details.