Why does the following code cause 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();
}
}
}
Output:
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)
Try Class c = Class.forName("tests.App02$A")
. It's not a top-level class, so use $ to locate it.
You need to use $
to access the nested class :
Class c = Class.forName("tests.App02$A");
When you compile your class, you will notice that the nested class is named as: App02$A.class
, under package tests
. It would make more sense then.
Because you are using a canonical name , but you should use name ( A.class.getName()
).
In your case you should use Class c = Class.forName("tests.App02$A");
在 commons-lang 中有一个有用的 util 支持这些类:
org.apache.commons.lang3.ClassUtils.get("tests.App02.A")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.