为什么无法加载内部类?ClassNotFoundException

为什么以下代码会导致?ClassNotFoundException

public class App02 {

    public static class A {
    }

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

        try {
            System.out.println("A.class.getCanonicalName() = " + A.class.getCanonicalName());
            Class c = Class.forName("tests.App02.A"); //error on this line
            System.out.println(c.getName());
        }

        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

输出:

A.class.getCanonicalName() = tests.App02.A
java.lang.ClassNotFoundException: tests.App02.A
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:190)
    at tests.App02.main(App02.java:15)

答案 1

尝试。它不是顶级类,因此请使用 $ 来查找它。Class c = Class.forName("tests.App02$A")


答案 2

您需要 使用 来访问嵌套类$

Class c = Class.forName("tests.App02$A");

编译类时,您会注意到嵌套类在 package 下被命名为:,这样会更有意义。App02$A.classtests


推荐