• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the use of Class.forName?  RSS feed

 
Ranch Hand
Posts: 189
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know why we use Class.forName() is used, not only from JDBC point of view but also generally. I am aware that in JDBC the driver class is loaded by using Class.forName(). Why not include the jar in your project and import it instead?
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
raja singh kumar wrote:Why not include the jar in your project and import it instead?


First, including the jar file, and importing it wouldn't guarantee that the class be loaded. You actually need to do something to cause the class to be loaded -- as the JVM won't load a class that it doesn't need.

raja singh kumar wrote:I want to know why we use Class.forName() is used, not only from JDBC point of view but also generally. I am aware that in JDBC the driver class is loaded by using Class.forName().


Well, IMHO, I would argue that it was originally a bad design. It is the straightforward solution, as the JDBC driver needs to be load into the DriverManager, so why not just load it? And have a static initializer that registers itself with the DriverManager? The problem however, is that it looks confusing as heck, as nothing else in Java really did this.

Luckily, this has been fixed... I believe around Java 6 or 7, and with JDBC 4.0, as there is now a mechanism for the DriverManager to auto search for the providers... but of course, everyone is still used to the old way of loading the drivers, as that is the norm...


As for forName() in general, that method is part of the reflection package. To learn more about that, you can look at the Oracle tutorial regarding it... https://docs.oracle.com/javase/tutorial/reflect/

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