ClassNotFoundException:当我尝试使用 Reflect 获取 class 时

ClassNotFoundException: when I try to get a class with Reflect

这是我的文件:

$ tree
.
├── Main.java
└── life
    └── Person.java

Main.java

import life.Person;

public class Main { 
  public static void main(String[] args) { 
    Person p = new Person();
    p.sayHi();
  } 
}

然后我尝试编译这段代码:

$ javac Main.java -d .
$ java Main
hello world

是的,这很好。但是当我尝试使用反射时,我将 Main.java 更改为:

import life.Person;

public class Main { 
  public static void main(String[] args) { 
    Class person = Class.forName("life.Person");
  } 
}

并且编译器抛出错误:

$ javac Main.java -d .
Main.java:6: error: unreported exception ClassNotFoundException; must be caught or declared to be thrown
    Class person = Class.forName("life.Person");

我很困惑,为什么这段代码先成功后失败?

为什么 class 找不到?

ClassNotFoundException是checked exception,这意味着语句可能会在运行时抛出ClassNotFoundException,你需要在编译阶段确定如何处理它。

可以在main方法中抛给调用者:

public static void main(String[] args) throws ClassNotFoundException

或使用 try catch 块:

try {
    Class person = Class.forName("life.Person");
} catch(ClassNotFoundException e) {
     // handle it
}

这并不是说找不到您的 class;这意味着 "I might throw a checked exception and you need to catch it"。

import life.Person;

public class Main { 
  public static void main(String[] args) { 
    try {
        Class person = Class.forName("life.Person");
    } catch (Exception e) {
        System.err.println(e);
    }
  } 
}