A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading).
EXAMPLE:
package com.bean;
class test{
static{System.out.println("this is static block of test");}
test(){System.out.println("this is test constructor");}
}
public class demo {
public static void main(String[] args)throws Exception{
//test t=new test();
System.out.println("start of demo");
Class c=Class.forName("com.bean.test");
System.out.println("class test loaded");
test obj=(test)c.newInstance();//create an instance
}
}
Output:
start of demo
this is static block of test
class test loaded
this is test constructor
Class.forName("X") loads the class if it not already loaded. If the class is already loaded then it does not do anything.
In the above example remove the comment from {test t=new test();}
Now this line loads the class so the class.forname() will not do anything.
You will see the output like this,
this is static block of test
this is test constructor
start of demo
class test loaded
this is test constructor
Here the static block is executed when the instance is created by by the new line(test t=new test()). After that the Class.forName() is called so now It has nothing to do because the class is already loaded.
JDBC driver is a good example of it,
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url,?myLogin", "myPassword");
All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.
The MySQL JDBC Driver has a static initializer looks like this:
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
JVM executes the static block and the Driver registers itself with the DriverManager.
No comments:
Post a Comment