I have a query.The function forName(String className) of java.lang.Class returns class object associated with the given string.Every return type must be caught.But if I write a programm such as
public class Demo{ public static void main(String arg[]){ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//this function returns class object /* code to manipulate database */
} }
Eventhough I have not caught the returned class object as Class m = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"), the program working fine.I just want to know how is this possible.Please clarify my doubt.
A 'side effect' of this method is that it causes the Class to be loaded, but only if it has not already been loaded. The trick here is that a Driver has a 'static block' which is a section of code that gets run when the class loads.
Therefore the forName() loads the Class, the static block fires, and the Driver registers itself with the DriverManager. This only gets done once, since the Class won't be loaded again.
Sujith Kanaparthi
Ranch Hand
Joined: Sep 04, 2005
Posts: 45
posted
0
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
but what happens to the returned value of the above method call? where is it going to be stored ?
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35223
7
posted
0
It's not stored anywhere. Since there is no assignment, the compiler will discard the object.
Class.forName(jdbc dbc:YourDriver) actually work this way: YourDriver is a class which has a static block in that static block you are creating the instance of YourDriver class which in turn will call the DriverManager.registerDriver and hence will get registerd with the DriverManager as DriverManager maintains the list of all the drivers registered with it. Something like this class YourDriver implements Driver { static { YourDriver d = new YourDriver(); DriverManager.registerDriver(d); } }
Instead of writing Class.forName(jdbc dbc:YourDriver) you can also write a command on the command prompt like this jdbc.drivers = jdbc dbc:YourDriver :jdbc dbc:YourDriver2:jdbc dbc:YourDriver3 and so on by this you are actually adding the Drivers to the java.lang.System property so when the DriverManager class is intialized it looks for jdbc.drivers if user has entered drivers then it will load them, by this you can specify more then one driver seprated with :
Instead of writing Class.forName(jdbc dbc:YourDriver) you can also write a command on the command prompt like this jdbc.drivers=jdbc:odbc:YourDriver:jdbc:odbc:YourDriver2:jdbc:odbc:YourDriver3
Not quite right. You can put them as -D options, and they have to be the Driver class, not the JDBC URL eg