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

6.9k views Asked by At

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?

5

There are 5 answers

2
Noon Silk On BEST ANSWER

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

0
Michael Borgwardt On

In your specific example, the JDBC driver class contains a static intializer that registers the driver will the DriverManager.

0
Bombe On

In the case of JDBC drivers the static initializer of the requested class will register the driver with JDBC’s DriverManager so that getting a connection for a driver-specific URL works.

2
Jesper On

This is used in particular for JDBC drivers. The JDBC driver class has a static initializer block that registers the class with the JDBC DriverManager, so that DriverManager knows about the driver when you later open a database connection.

In a newer version of JDBC (JDBC 3.0, I think) this is not necessary anymore, a different mechanism is used by DriverManager to find JDBC drivers.

edit - This page explains in detail how loading a JDBC driver works and how the driver registers itself with the DriverManager (the old way).

0
ZZ Coder On

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.