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

走远了吗. 提交于 2019-12-06 07:56:48

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.

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.

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.

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

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