Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Class.forName() work?

Tags:

java

jdbc

I just learned about java.sql package. It uses Class.forName() to dynamically load the driver which extends DriverManager. Then we get connection using DriverManager.getConnection() method.

So how does the entire thing work?
How does DriverManager class know how to get the connection without using class name of the actual driver.

Also can we use Class.forName() for custom applications... if this is explained with an example I will be very happy.

like image 562
SonOfTheEARTh Avatar asked Nov 17 '10 07:11

SonOfTheEARTh


People also ask

What is the role of Class forName () in JDBC?

Use the Class. forName() method to load the driver. The forName() method dynamically loads a Java class at runtime. When an application calls the forName() method, the Java Virtual Machine (JVM) attempts to find the compiled form (the bytecode) that implements the requested class.

What is the actual purpose of Class forName () method Mcq?

The forName() method of Java Class class returns the Class object associated with the class or interface with the given name in the parameter as String.

Which type of exception will be thrown by forName () method?

forName() method may throw an exception at the time of returning a Class object. LinkageError: This exception may throw when we get linking error. ExceptionInInitializeError: In this exception when the initialization is done by this method fails.

How do I find the Class forName?

The forName() method of java. lang. Class class is used to get the instance of this Class with the specified class name. This class name is specified as the string parameter.


1 Answers

Class.forName simply loads a class, including running its static initializers, like this:

class Foo {     static {         System.out.println("Foo initializing");     } }  public class Test {     public static void main(String [] args) throws Exception {         Class.forName("Foo");     } } 

All the rest of the procedure you're talking about is JDBC-specific. The driver - which implements Driver, it doesn't extend DriverManager - simply registers an appropriate instance using DriverManager.registerDriver. Then when DriverManager needs to find a driver for a particular connection string, it calls connect on each registered driver in turn until one succeeds and returns a non-null connection.

Note that this way of registering drivers is reasonably old-fashioned - look at the docs for DriverManager for more modern ways of getting at a data source.

like image 152
Jon Skeet Avatar answered Oct 23 '22 14:10

Jon Skeet