在 Eclipse 中使用反射 "Class.forName" 时出错

Error using Reflection "Class.forName" in Eclipse

我正在尝试借助 Eclipse IDE 书中的示例编译反射示例:

public class Reflection_Test {

    public static void main(String[] args) {

        // In both cases below, "ClassNotFoundException" occurs
        Class c1 = Class.forName("java.util.Date");
        Class c2 = Class.forName("Foo");
    }

}

class Foo {
    // ...
}

我完全复制了该行,但这引发了两个异常。我用谷歌搜索了其他问题,他们建议使用正确的包名。但就我而言,我是在 默认包 下编译它的。它缺少什么?

forName 方法抛出 ClassNotFoundException。您需要在代码中处理它,否则代码将无法编译。

这可能是因为:

  • 您没有注意到主方法签名中的 throws ClassNotFoundException
  • 他们没有费心在示例中用 try catch 块包围该块
  • 样本没有用 try catch 围绕代码,目的是为了说明一个想法,稍后揭示块的目的

运行 它确实会为 Foo class 抛出 ClassNotFoundException。 只有当您的 Reflection_Test class 声明了一个包时才会发生这种情况,在这种情况下您将需要 Foo 的完全限定名称。

否则,如果没有显式包,只要您如上所述使其可编译,它就会工作。

正在使用

public class Reflection_Test {

    public static void main(String[] args) {
        try {
          Class c1 = Class.forName("java.util.Date");
          Class c2 = Class.forName("Foo");

          java.util.Date date = (java.util.Date)c1.newInstance();
          Foo foo = (Foo)c2.newInstance();

          foo.bar(date);
        } catch (Throwable te) {
          System.out.println(te);
        } 
    }

}

class Foo {
  public void bar(java.util.Date date) {
    System.out.println("Hello, world! The date is " + date);
  }
}

修复了编译错误并且

$ javac Reflection_Test.java
$ java Reflection_Test

给出输出

Hello, world! The date is Wed Jul 29 15:39:32 CEST 2015

符合预期。

原来编译出现问题是因为Class.forName(String className) is declared to throw a ClassNotFoundException and the compile-time checking of exceptions in Java requires you to handle this exception (by either catching it or declaring it in the throws clause of the method) as it is a so-called checked exception.

注意:您可能需要比

稍微更精细的错误处理方法
catch (Throwable te) {
  ...
}

通过捕获特定的异常,特别是 ClassNotFoundException(但我很懒,我通过创建实例来扩充示例,所以也会有 InstantiationExceptionIllegalAccessException需要被抓住)。