27

一个 Thinking in Java 程序如下:

package typeinfo;
import static util.Print.*;

class Candy {
 static { print("Loading Candy"); }
}

class Gum {
 static { print("Loading Gum"); }
}

class Cookie {
 static { print("Loading Cookie"); }
}

public class SweetShop {
 public static void main(String[] args) {  
   print("inside main");
   new Candy();
   print("After creating Candy");
   try {
     Class.forName("Gum");
   } catch(ClassNotFoundException e) {
     print("Couldn't find Gum");
   }
   print("After Class.forName(\"Gum\")");
   new Cookie();
   print("After creating Cookie");
 }
} 

我期待输出如下:

/* Output:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
*/

但是得到

inside main
Loading Candy
After creating Candy
Couldn't find Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie

显然,try 块抛出了一个 ClassNotFoundException,这是出乎意料的。任何想法为什么代码抛出这个而不是初始化 Gum 类,如预期的那样?

4

1 回答 1

68

您的类在 packagetypeinfo中,因此它们的完全限定名称是typeinfo.Gum,typeinfo.Candytypeinfo.CookieClass.forName()只接受完全限定名称:

参数:

className- 所需类的完全限定名称。

将您的代码更改为:

try {
  Class.forName("typeinfo.Gum");
} catch(ClassNotFoundException e) {
  print("Couldn't find Gum");
}
于 2013-03-14T18:24:29.800 回答