Sunday, October 23, 2011

How Class.forName() method works ?


How Class.forName() method works ?

Class.forName()

  1. Class.forName("XYZ"method dynamically loads the class XYZ (at runtime).
  2. Class.forName("XYZ"initialized class named  XYZ (i.e., JVM executes all its static block after class loading). 
  3. Class.forName("XYZ"returns the Class object associated with theXYZ class. The returned Class object is not an instance of the XYZ class itself.

Class.forName("XYZ")loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. The XYZ is the fully qualified name of the desired class.

For example,

  1. package com.usebrain.util;  
  2.   
  3. public class LoadClass {  
  4.  static {  
  5.   System.out.println("************LoadClass static block************");  
  6.  }  
  7. }  

  1. package com.usebrain.action;  
  2.   
  3. public class Test {  
  4.   
  5.  public static void main(String[] args) {  
  6.   try {  
  7.    Class c = Class.forName("com.usebrain.util.LoadClass");  
  8.   } catch (ClassNotFoundException e) {  
  9.    e.printStackTrace();  
  10.   }  
  11.  }  
  12. }  

Example that use returned Class to create an instance of  LoadClass:

  1. package com.usebrain.util;  
  2.   
  3. public class LoadClass {  
  4.  static {  
  5.   System.out.println("************LoadClass static block************");  
  6.  }  
  7.    
  8.  public LoadClass() {  
  9.      System.out.println("*************LoadClass Constructor************");  
  10.    }  
  11. }  

  1. package com.usebrain.action;  
  2.   
  3. import com.usebrain.util.LoadClass;  
  4.   
  5. public class Test {  
  6.   
  7.  public static void main(String[] args) {  
  8.   
  9.   try {  
  10.    System.out.println("first time calls forName method");  
  11.   
  12.    Class loadObj = Class.forName("com.usebrain.util.LoadClass");  
  13.    LoadClass loadClass = (LoadClass) loadObj.newInstance();  
  14.   
  15.    System.out.println("\nsecond time calls forName method");  
  16.    Class.forName("com.usebrain.util.LoadClass");  
  17.   
  18.   } catch (InstantiationException e) {  
  19.    e.printStackTrace();  
  20.   } catch (IllegalAccessException e) {  
  21.    e.printStackTrace();  
  22.   } catch (ClassNotFoundException e) {  
  23.    e.printStackTrace();  
  24.   }  
  25.  }  
  26. }  

Output
first time calls forName method
************LoadClass static block************
*************LoadClass Constructor************

second time calls forName method

No comments:

Post a Comment