Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion in Class.forName() :confused:

 
Glenny Dsilva
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read that Class.forName() is to load the class dynamically.

And one of the places it is used is to load the Driver in jdbc.

for e.g.

Class.forName("com.mysql.jdbc.Driver");

But instead of the above code can i just use

package com.mysql.jdbc.Driver;

Why do i need to use Class.forName() (i.e. load it dynamically);

Pls. explain
 
Darryl Nortje
Ranch Hand
Posts: 140
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
--> I have read that Class.forName() is to load the class dynamically.
--> And one of the places it is used is to load the Driver in jdbc.
--> for e.g.
--> Class.forName("com.mysql.jdbc.Driver");

Normally what you will do is have the driver in a properties file and then call Class.forName(myDriverProperty); That way by changing the value in the properties file you will be loading a different jdbc driver

--> But instead of the above code can i just use
--> package com.mysql.jdbc.Driver;

I think you mean import com.mysql.jdbc.Driver ??

so what do you do if you now want to use a postgres database driver.
You have to change and recompile your code to now import org.postgresql.Driver.

--> Why do i need to use Class.forName() (i.e. load it dynamically);
That's exactly why you need Class.forName(). To load the class dynamically. IE: No recompile necessary if you change databases.

cheers
Darryl
 
KasiMurugan Ramasamy
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guy,

import doesn't load the class until your first reference that class.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic