本文介绍了Class.forName()抛出ClassNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Thinking in Java程序如下:

A Thinking in Java program is as follows:

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

Obviously the try block is throwing a ClassNotFoundException, which is unexpected. Any ideas why the code throws this instead of initializing the Gum class, as expected?

推荐答案

你的类在包中 typeinfo ,因此他们的完全限定名称是 typeinfo.Gum typeinfo.Candy typeinfo.Cookie 。 只接受完全限定名称:

Your classes are in the package typeinfo, so their fully-qualified names are typeinfo.Gum, typeinfo.Candy and typeinfo.Cookie. Class.forName() only accepts fully-qualified names:

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

className - the fully qualified name of the desired class.

将您的代码更改为:

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

这篇关于Class.forName()抛出ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:10