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

限于喜欢 提交于 2019-11-27 19:47:04

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

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.

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

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).

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.

to manul load class in current classloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!