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类?

最佳答案

您的类(class)在typeinfo包中,因此它们的完全限定名称为typeinfo.Gumtypeinfo.Candytypeinfo.Cookie Class.forName() 仅接受标准名称:

将您的代码更改为:

try {
  Class.forName("typeinfo.Gum");
} catch(ClassNotFoundException e) {
  print("Couldn't find Gum");
}

09-11 19:12