Java类找不到异常 – java.lang.ClassNotFoundException
Java中的ClassNotFoundException
- Java ClassNotFoundException occurs when the application tries to load a class but Classloader is not able to find it in the classpath.
- Common causes of java.lang.ClassNotFoundException are using Class.forName or ClassLoader.loadClass to load a class by passing String name of a class and it’s not found on the classpath.
- ClassNotFoundException is a checked exception, so it has to be catch or thrown to the caller.
- ClassNotFoundException always occurs at runtime because we are indirectly loading the class using Classloader. Java compiler has no way to know if the class will be present in the classpath at runtime or not.
- One of the most common example of ClassNotFoundException is when we try to load JDBC drivers using Class.forName but forget to add it’s jar file in the classpath.
Java 类找不到异常示例
我们来看一个简单的例子,其中我们将会得到ClassNotFoundException。
package com.Olivia.exceptions;
public class DataTest {
public static void main(String[] args) {
try {
Class.forName("com.Olivia.MyInvisibleClass");
ClassLoader.getSystemClassLoader().loadClass("com.Olivia.MyInvisibleClass");
ClassLoader.getPlatformClassLoader().loadClass("com.Olivia.MyInvisibleClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
请注意,com.Olivia.MyInvisibleClass并不存在,所以当我们执行以上程序时,会得到以下异常堆栈跟踪。
java.lang.ClassNotFoundException: com.Olivia.MyInvisibleClass
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:292)
at com.Olivia.exceptions.DataTest.main(DataTest.java:7)
在上述示例中,所有三个语句都会引发java.lang.ClassNotFoundException异常。
如何解决ClassNotFoundException
修复ClassNotFoundException非常容易,因为异常堆栈中明确指定了找不到的类。只需检查类路径设置,并确保类在运行时存在即可。
类找不到异常 vs 类定义未找到错误
当一个类在运行时找不到时,NoClassDefFoundError是一个运行时错误。它与ClassNotFoundException非常相似。在Java NoClassDefFoundError中了解更多。 参考:API文档