Search code examples
javajavac

ClassNotFoundException: when I try to get a class with Reflect


This is my files:

$ 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();
  } 
}

And I try to compile this code:

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

Yeah, this was fine. But when I try to use reflect, so I change my Main.java to this:

import life.Person;

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

And compiler throw an error:

$ 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");

I am very confused, why this code success first and failed in the next?

Why class not found?


Solution

  • ClassNotFoundException is a checked exception, it means the statement might throw ClassNotFoundException at run time and you need determine how to handle it at compile stage.

    You can throws it to the caller in main method:

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

    or use a try catch block:

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