What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

java, jdbc

Solution

It obtains a reference to the class object with the FQCN (fully qualified class name) `oracle.jdbc.driver.OracleDriver`.

It doesn't "do" anything in terms of connecting to a database, aside from ensure that the specified class is loaded by the current classloader. There is no fundamental difference between writing

Class<?> driverClass = Class.forName("oracle.jdbc.driver.OracleDriver");
// and
Class<?> stringClass = Class.forName("java.lang.String");

`Class.forName("com.example.some.jdbc.driver")` calls show up in legacy code that uses JDBC because that is the legacy way of loading a JDBC driver.

From The Java Tutorial:

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method `Class.forName`. This methods required an object of type `java.sql.Driver`. Each JDBC driver contains one or more classes that implements the interface `java.sql.Driver`. ... Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method `Class.forName`.)

Further reading (read: questions this is a dup of)

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

- How does Class.forName() work?

- What does 'Class.forName("org.sqlite.JDBC");' do?

- What is the purpose of 'Class.forName("MY_JDBC_DRIVER")'?

- Loading JDBC driver

Problem

What will the command ``` Class.forName("oracle.jdbc.driver.OracleDriver") ``` exactly do while connecting to a Oracle database? Is there an alternate way of doing the same thing?

Original source

Related problems