• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class.forName

 
Shrawan Bhageria
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Please explain this.

1>how many ways we can load the driver in jdbc?
2>whats the class.forName(....) do xactly?


Thanks and Regards,

Shrawan
 
Saket Barve
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JDBC driver can be loaded in two ways:
1. Specify the driver(s) on the command line when running your java code, using the colon as a driver-separator:


2. Load the driver from within your application:


As you can see, the Class.forName() performs the task of loading the driver at runtime.
 
Muhammad Saifuddin
Ranch Hand
Posts: 1324
Android Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shrawan Bhageria:

whats the class.forName(....) do xactly?


Using Class.forName will create and initialize an instance of the class you pass in as a paramter. So using Class.forName will achieve the same result as creating an instance of the class and initializing it yourself. The benefits of using Class.forName are that the forName method throws a ClassNotFoundException, so in the case that the classes do not exist that you are trying to use, a ClassNotFoundException will be thrown and since you can't call the forName method without handling the exception in some way (catching or throwing the exception), your application will be better suited to handle this scenario whereas creating instances of the class yourself will not have this benefit (your application will have an unhandled exception and exit). Reference
 
Joice Jose
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If Class.forName will create and initialize an instance of the class you pass, then why not the below program print "Hi making instance of the class.......". But if we use ' new abc(); ' it will print.

public class abc
{
public abc()
{
System.out.println("Hi making instance of the class.......");
}

public static void main(String str[])
{
try {
Class.forName("abc");
}catch(ClassNotFoundException e) {
System.out.println("Hi class not found ......." + e);
}
}
}
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34073
335
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joice,
Good question!

There's a difference between initializing and instantiating. When you load a class into memory (which Class.forName() does), it initializes itself by setting up any static variables. When you instantiate a class, you load it into memory, initialize it and the create an instance.

The JavaDoc for ExceptionInInitializer explains the static intializer relationship a bit more.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic