问题
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?
回答1:
It performs a static loading of that class. So anything in the static { } block, will run.
回答2:
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.
回答3:
In your specific example, the JDBC driver class contains a static intializer that registers the driver will the DriverManager.
回答4:
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).
回答5:
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.
回答6:
to manul load class in current classloader
来源:https://stackoverflow.com/questions/1310494/what-purpose-does-class-forname-serve-if-you-dont-use-the-return-value