问题
I am learning to enable my Java application to communicate with a MS Access database.
I am unsure of one method, the Class.forName() method. The parameter I pass is "sun.jdbc.odbc.JdbcOdbcDriver", which loads the jdbc:odbc bridge for accessing a database.
What does the Class.forName() do exactly and why is it needed?
Thank you very much.
回答1:
Class.forName()
causes ClassLoader to load the class into memory. JDBC driver classes have static initializers that register them with DriverManager for further use. After you use Class.forName()
, and use DriverManager.getConnection("jdbc:*", database, username, password)
, the jdbc:
is already loaded in memory.
回答2:
Class.forName()
is used for loading class dynamically. For example you called Class.forName("z")
, this will cause the class z to get initialized and corresponding object will be returned.
回答3:
Class.forName() uses reflection to load the class of the given name. It returns a Class object. See this.
In your case, it allows you to load a specific driver at runtime, without hardcoding the driver type. You just have to pass the driver name as a parameter.
回答4:
It uses reflection
to instantiate sun.jdbc.odbc.JdbcOdbcDriver
class, using the class name in String format.
This makes your code Driver
class independent and allows you to pass the driver class name externally as a String parameter (which is standard behavior as we pass the connection details through configuration).
来源:https://stackoverflow.com/questions/13533071/what-does-forname-method-in-the-class-class-do-when-loading-jdbcodbc-driver