ClassNotFoundException xảy ra khi ClassLoader không tìm thấy class tại đường dẫn được chỉ định. Điều này thường xảy ra khi:
- Tải class rõ ràng qua
Class.forName()hoặcClassLoader.loadClass(). - Chạy chương trình Java với classpath không đúng.
Các nguyên nhân phổ biến
- Tên class/package sai chính tả khi truyền cho
forName(). - Classpath không chứa thư mục/chứa file .class hoặc file JAR cần thiết.
- Chạy từ thư mục sai so với nơi chứa package root.
Ví dụ minh họa
Giả sử class Sample nằm trong package myPackage.example tại D:/:
package myPackage.example;
public class Sample {
static {
System.out.println("The class named Sample loaded successfully.........");
}
}
Biên dịch: javac -d . Sample.java (tạo thư mục myPackage/example/Sample.class tại D:/)
Trường hợp 1: Sai tên package
public class ClassNotFoundExample {
public static void main(String args[]) {
try {
Class.forName("myPackage.exampl.Sample"); // Thiếu 'e' ở 'example'
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
java.lang.ClassNotFoundException: myPackage.exampl.Sample
Trường hợp 2: Đúng tên nhưng classpath sai
Chạy từ thư mục E:/ mà không set classpath:
E:\>java ClassNotFoundExample java.lang.ClassNotFoundException: myPackage.example.Sample
Cách khắc phục
Set classpath trỏ đến thư mục chứa package root (ở đây là D:/):
E:\>java -cp D:\ ClassNotFoundExample The class named Sample loaded successfully.........
Mẹo: Dùng java -cp .:path/to/jar com.package.MainClass (Linux/Mac) hoặc java -cp .;path\to\jar com.package.MainClass (Windows).