• Post Reply Bookmark Topic Watch Topic
  • New Topic

use of Class.forName()?  RSS feed

 
anish jain
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read that Class.forName() loads the class which means that static variables will be initialized and static blocks present in the class will be executed.
Could you please tell me the situations(except jdbc driver loading) where we need to use it ???
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you want to work with JDBC, you need to touch the Driver class using Class.forName("com.mysql.jdbc.Driver");

When the static block run, the Driver class makes some registrations to the DriverManager or something. This is why it's vital to touch the class before you obtain a connection.
 
anish jain
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian Janisch wrote:When you want to work with JDBC, you need to touch the Driver class using Class.forName("com.mysql.jdbc.Driver");

When the static block run, the Driver class makes some registrations to the DriverManager or something. This is why it's vital to touch the class before you obtain a connection.


except JDBC, could you please tell me any other situation where we may have to use Class.forName()
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any time you need to do the same thing.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use it to dynamically load classes, i.e. classes that your program needs to use, but of which you don't know the class name beforehand (at compile time). It's useful for plugin systems, for example. The JDBC driver is a good example: your program should not need to know at compile time which JDBC driver has to be used; it should be possible to change to a different driver without recompiling your program.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!