What does forName() method in the Class class do, when loading jdbc:odbc driver?

岁酱吖の 提交于 2019-12-22 18:58:08

问题


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

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