Saturday, April 09, 2011

Class.forName() Method and Dynamic Class Loading

This is an Interesting Conversation in DevX Form – click here for details.

Question :I have a doubt regarding the working of Class.forName() method.
How exactly it works in jvm? What is the difference between
Class.forName(“oracle.jdbc.driver.OracleDriver”) & DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())?
If my JDBC code is something like this:
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Class.forName(“Some other driver class”);
Connection conn = DriverManager.getConnection(“jdbcracle:thin:@hostname:1521:SID”,”user”, “pwd”);

Which class will be loaded and how will DriverManager class will know which driver to communicate?

Answer : Short Answer (Summary)

  • Both Drivers will be loaded and they register themselves by calling DriverManager.registerDriver() method, and based on the connection URL provied the approriate driver is loaded
  • When we instantiate a Object with “new” keyword 2 things happen
    (1)Load the class in to memory, if it is not loaded -
    which means creating in-memory representation of the class from the .class file so that an instance can be created out of it. This includes initializing static variables (resolving of that class)

(2)create an instance of that class and store the reference to the variable.

  • Class.forName does only the first thing.It loads the class in to memory and return that reference as an instance of Class. If we want to create an instance then, we can call newInstance method of that class. which will invoke the default constructor (no argument constructor). BUT The main advantage of using Class.forName is that it takes the class name as a String, so we can change the JDBC Driver at run time by passing a different JDBC driver from a property file or command line. We have to make sure we also pass the Connection url (which is also a String) based on the DB if the DB is changed, there can be cases where the DB is not changed but the dbc driver is changed.

No comments: