Why do we use Class.forName() for loading JDBC Drivers?

I have blogged about The Class & The ClassLoader here and in that blog entry I have mentioned about different ways of getting Class instances. May be I will repeat it.

  • Class<?> c = ClassName.class;
  • Class<?> c = object.getClass();
  • Class<?> c = Class.forName(“ClassName”);
  • Class<?> c = loader.loadClass(“ClassName”);

Class<?> c = object.getClass() is of no use in this context as we are using an already loaded class’s Object.

Class<?> c = loader.loadClass(“ClassName”) will load the class but will not initialize it. This method is mainly used in contexts where we have to analyse the meta information of the class.

Class<?> c = ClassName.class which is equivalent to Class.forName(“ClassName”, false, loader), the method signature is like Class.forName(String name, boolean initialize, ClassLoader loader) this method will in turn call the method forName0(String name, boolean initialize, ClassLoader loader) where name is the fully qualified name, initialize decides whether the class should be initialized or not and loader for loading the class. What happens with this method is that the loader will load the class and if initialize is true it will initialize the class. So with ClassName.class also the class will not be initialized.

Class<?> c = Class.forName(“ClassName”), this method will call the method forName0(“ClassName”, true, callerClassLoader) as I explained earlier the class loader will load the class and by seeing initialize as true it will initialize the class.

Earlier most of the JDBC Drivers had to register themselves to the DriverManager and most probably the code which does the registration will be in a static block, so the only way to get it registered before we can use it is to initialize the class and there by running the static block. To load the class and initialize it programatically there is no best option other than using the Class.forName().

Any way now we don’t have to explicitly call Class.forName() as DriverManagers follow the service provider mechanism (It will look for a file named java.sql.Driver inside META-INF/services. The file contains the names of Drivers separated by new line). DriverManager will find the suitable driver using this data. Another thing is that nobody uses DriverManager these days as Datasource  is the preffered way of obtaining a connection.

Similar Posts:

    No similar blogs

Related Posts

Stay UpdatedSubscribe and Get the latest updates from Vafion