Sunday, December 30, 2012

Reflection - Class.forname(String s)

Reflection

Here is one example that uses returned Class to create an instance of AClass:
package com.xyzws;
class AClass {
  public AClass() {
    System.out.println("AClass's Constructor");
  }
  static { 
    System.out.println("static block in AClass");
  }
}
-------------------------------------------------------

public class Program { 
  public static void main(String[] args) {
    try { 
      System.out.println("The first time calls forName:");
      Class c   = Class.forName("com.xyzws.AClass"); //return the Class object (Every Class has an class object)
      AClass a = (AClass)c.newInstance(); //create a Instance using this Object

      System.out.println("The second time calls forName:");
      Class c1 = Class.forName("com.xyzws.AClass");

    } catch (ClassNotFoundException e) {
            ...
    } catch (InstantiationException e) {
            ...
    } catch (IllegalAccessException e) {
            ...
    }
        
  }
}
The output is
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:  
//Calss has been loaded so there is not "static block in AClass" printing out

Why use reflection?
You can decide whether or not to create an instance at runtime.
if "com.xyzws.AClass" exist -> create 
else not create anything

Struts 2 权威指南 P606 DAO factory 使用了这种方法,使得系统添加DAO组件时,无需修改代码,只需要在DD里面加入就行了。

No comments:

Post a Comment