Originally posted by Ritu Kapoor:
Hi,
Class.forName() is generally used to load classes dynamically, a general use of this method is to load a driver. My question is:
1. What exactly happens when we call Class.forName("DriverName");. How a driver gets loaded by calling this method.
2. How a DriverManager comes to know that a driver has been loaded when we call DriverManager.getConnection(url,login,pwd);
I need an elaborated view on this. Kindly help me to understand the logic.
Regards,
Ritu
Did you by any chance have an interview with Accenture Bangalore?
Ulf has supplied your answer.
The second approach is not used because it tightly couples your code to the Driver class whereas the first approach provides you a level of indirect and enables you to NOT care about the Driver class until runtime.
I hope that gives you some insights...
anyway, this is something you must read-
The Java SQL framework allows for multiple database drivers.
Each driver should supply a class that implements the Driver interface.
The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.
It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast quantities of supporting code.
When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling
Class.forName("foo.bah.Driver")
- from the API Docs for java.sql.Driver