Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What purpose does Class.forName() serve if you don't use the return value?

Tags:

I've seen this line in a sample application for using a commercial JDBC driver:

Class.forName("name.of.a.jcdb.driver") 

The return value is not used.

What purpose does this line serve?

like image 227
Daniel Rikowski Avatar asked Aug 21 '09 07:08

Daniel Rikowski


People also ask

What is the purpose of class forName method?

forName. Returns the Class object associated with the class or interface with the given string name, using the given class loader. Given the fully qualified name for a class or interface (in the same format returned by getName ) this method attempts to locate, load, and link the class or interface.

Why do we write class forName () in JDBC?

forName() The most common approach to register a driver is to use Java's Class. forName() method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.

Is class forName required?

forName() is no longer required. Since Java 1.6, JDBC 4.0 API, it provides a new feature to discover java. sql. Driver automatically, it means the Class.

What is the role of class forName while loading drivers?

forName will do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.


2 Answers

It performs a static loading of that class. So anything in the static { } block, will run.

like image 152
Noon Silk Avatar answered Sep 20 '22 05:09

Noon Silk


Maybe some code snippet will help. This is from Sun's JDBC-ODBC bridge driver,

//-------------------------------------------------------------------- // Static method to be executed when the class is loaded. //--------------------------------------------------------------------   static {            JdbcOdbcTracer tracer1 = new JdbcOdbcTracer();     if (tracer1.isTracing ()) {         tracer1.trace ("JdbcOdbcDriver class loaded");     }      JdbcOdbcDriver driver = new JdbcOdbcDriver ();      // Attempt to register the driver      try {         DriverManager.registerDriver (driver);     }     catch (SQLException ex) {         if (tracer1.isTracing ()) {             tracer1.trace ("Unable to register driver");         }       } } 

the DriverManager.registerDriver() call in a static block is executed whenever the driver is loaded through Class.forName().

This used to be the only way to register the driver. JDBC 4.0 introduced a new service registration mechanism so you don't need to do this anymore with newer JDBC 4.0 compliant drivers.

like image 33
ZZ Coder Avatar answered Sep 23 '22 05:09

ZZ Coder