<Think in java >這本書的實例代碼。java
例子1、ide
package com.yuan.test; //: typeinfo/SweetShop.java //Examination of the way the class loader works. class Candy { static { System.out.println("Loading Candy"); } } class Gum { static { System.out.println("Loading Gum"); } } class Cookie { static { System.out.println("Loading Cookie"); } } public class SweetShop { public static void main(String[] args) { System.out.println("inside main"); new Candy(); System.out.println("After creating Candy"); try { Class.forName("Gum"); } catch (ClassNotFoundException e) { System.out.println("Couldn’t find Gum"); } System.out.println("After Class.forName(\"Gum\")"); new Cookie(); System.out.println("After creating Cookie"); } } //輸出結果 inside main Loading Candy After creating Candy Couldn’t find Gum After Class.forName("Gum") Loading Cookie After creating Cookie
//仔細研究了一下以後,對Class.forname(0的使用方法有了一些瞭解。例子一中沒有找到Gum類的緣由是,我在Class.forname("這裏面沒有指明類文件包文件名稱+類名稱")。我在例子二中給出了全名稱以後就能夠了。spa
例子2、code
package com.yuan.test; //: typeinfo/SweetShop.java //Examination of the way the class loader works. class Candy { static { System.out.println("Loading Candy"); } } class Gum { static { System.out.println("Loading Gum"); } public void getA(){ System.out.println("調用我哦!"); } } class Cookie { static { System.out.println("Loading Cookie"); } } public class SweetShop { public static void main(String[] args) { System.out.println("inside main"); new Candy(); System.out.println("After creating Candy"); try { Class c=Class.forName("com.yuan.test.Gum"); Object obj=null; System.out.println("123:"+c.getName()); Gum gum=(Gum)c.newInstance(); gum.getA(); } catch (ClassNotFoundException e) { System.out.println("Couldn’t find Gum"); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("After Class.forName(\"Gum\")"); new Cookie(); System.out.println("After creating Cookie"); } }
總結:Class.forname()實際上是得到類的申明。get
Class c=Class.forName("com.yuan.test.Gum");
要想調用類的方法得這樣作。使用 Class 的newinstance()方法來實例該類。io
Object obj=null; Gum gum=(Gum)c.newInstance(); gum.getA();