Saturday, 8 August 2015

Class.forname method

Class.forName("X") helps us to load class dynamically(at runtime) using its fully qualified name (package.classname) and JVM executes all its static block after class loading.

Note: It does not return the instance of Class.

forName() uses the classloader to invoke the class.

If a class already loaded in JVM, Class.forName()  does not load that class i.e. JVM keeps track of all the classes that have been previously loaded.

public class ClassForName {
       public ClassForName() {
              System.out.println("ClassForName Constructor");
       public static String methodName = "ClassForName";
       static {
              System.out.println("static block in ClassForName");

 class TestForname {
       public static void main(String[] args) {
              try {
                     Class c   = Class.forName("core.forname.ClassForName");
                     ClassForName name = (ClassForName)c.newInstance();
                     System.out.println("The second time calls forName:");
                  Class c1 = Class.forName("core.forname.ClassForName");

              } catch (InstantiationException | IllegalAccessException e) {
              } catch (ClassNotFoundException e) {
The output is
static block in ClassForName
ClassForName Constructor
The second time calls forName:

JDBC Driver Is a Good Example
We generally uses it load the JDBC Drivers.
If class successfully loaded, the static initializer is called.

Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...