• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between Class.forname(" ") and Class.forName(" ").newInstance()

 
Punit Jain
Ranch Hand
Posts: 1012
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is there any difference between



and



however in the second statement a instance of the Class is created but both are giving the same output, so i want to know is there any difference between both of them??


 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first only loads the class, the second also creates an instance. For some (mostly old) drivers this was necessary because the class wouldn't register itself properly without it. You're using an old driver though. The latest one is com.mysql.jdbc.Driver, and doesn't need the newInstance() call.
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You do not need an instance of the class. If your class has a private constructor, it may throw a (checked) Exception. You should miss out the newInstance call because you do not need the instance.
 
Punit Jain
Ranch Hand
Posts: 1012
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
means if i m using

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

i should not worry about newInstance().
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You do not need an instance of the class. If your class has a private constructor, it may throw a (checked) Exception. You should miss out the newInstance call because you do not need the instance.

If I recall correctly, a few quite old JDBC drivers actually did need an instance. They were poorly written to register the driver in the constructor, not a static block. These days that should definitely not be the case anymore.

Punit Jain wrote:means if i m using

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

i should not worry about newInstance().

Nope. Just drop it.
 
Punit Jain
Ranch Hand
Posts: 1012
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay..thanks...
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:You're welcome.
Same here
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic