Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class.forName()

 
paul wheaton
Trailboss
Pie
Posts: 21896
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does this *have* to be called to do jdbc? Is there no other way?
Plus, if I passed in some class that included a main() would that program run?
 
Doug Gschwind
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe that is the only way to support JDBC connectivity to an RDBMS. The primary reason being that any of the JDBC driver types simply live up to the JDBC interface. Thus, by dynamically loading the class of interest, you are selecting the JDBC driver you want supporting your JDBC calls.
No, main() would not run automatically on your behalf. You could initiate that behavior yourself by calling it directly.
 
paul wheaton
Trailboss
Pie
Posts: 21896
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So a class would have been loaded later if I did not load it at that point, right?
This just loads the class so that it is available to anyone that tries to use it. Right? There might be five classes all called the same thing available on my computer, but by loading it manually, I'm making sure that the one I need is loaded. Is that right?
 
Doug Gschwind
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul, I would imagine that your statement is correct. If you did not load it manually, the class loaded would find the first instance by name from your CLASSPATH and use that, if one was found.
The benefit of using forName() directly in source code then would be to guarantee that the specific JDBC driver desired is loaded.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to my notes from the Sun course "Distributed Programming w/Java" Sun used to actually suggest creating an instance of the driver without holding onto the reference. For instance:
new imaginary.sql.iMsqlDriver();
I penciled in "New and improved method" as:
Class.forName("com.imaginary.sql.msql.Msqldriver");
So...there are other ways of doing this.
 
Brent Worden
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of the main benefits to using Class.forName() is it make the code more maintainable. You can make the class name string configurable so the driver of your choosing is loaded. That way if you ever change your data source driver, you wouldn't have to change code and recompile for it to function.
Brent Worden
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic