• Post Reply Bookmark Topic Watch Topic
  • New Topic

Use of Class.forName()  RSS feed

 
Akhilesh Murthy
Ranch Hand
Posts: 31
1
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I wanted to know how Class.forName() works ?

I know it is used for JDBC connection but how does it work?

Thanks
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the documentation for that method, you'll see it says:
Returns the Class object associated with the class or interface with the given string name. ...
...A call to forName("X") causes the class named X to be initialized.

All that method does is load the named class, and return a Class object representing it. It doesn't do anything more than that. For JDBC drivers, the clever stuff happens in the class you're loading. They have static initializer blocks (which are run when the class is loaded) so that they register themselves with the DriverManager as drivers that can deal with certain connection URLs.

 
naresh San
Greenhorn
Posts: 7
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to know how Class.forName() works ?

I know it is used for JDBC connection but how does it work?


Class.forName will basically load a class which you specify as the String type arg(fully qualified name of the class). As part of class loading, static variables
will be initialized and static blocks present in the class will be executed.

forName() is the static method present in java.lang.Class i.e public static Class forName(String className) throws ClassNotFoundException

for Example

Class.forName("oracle.jdbc.driver.OracleDriver");

Here Class.forName loads the OracleDriver class present in oracle.jdbc.driver package and gets initialized.

This is the concept used in JDBC to register driver(s). A static block in the driver
class gets executed which registers the JDBC driver with the connection manager at run time.

OracleDriver.java

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!