String className ="test.Test1"; Class clazz; try { clazz = Class.forName(className); Test1 userDao=(Test1) clazz.newInstance(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); }
這裏className必須是完整的包名類名,另外這種方式經過Test1的這種方式進行實例化:
public Test1(){ System.out.println("new Test1"); }