How do I resolve ClassNotFoundException?
This is the best solution I found so far.
Suppose we have a package called org.mypackage
containing the classes:
- HelloWorld (main class)
- SupportClass
- UtilClass
and the files defining this package are stored physically under the directory D:\myprogram
(on Windows) or /home/user/myprogram
(on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld
. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
NOTE: You have to execute the above
java
command no matter what your current location is. But this is not the case forjavac
. For compiling you can even directly go into the directory where you have your.java
files and directly executejavac ClassName.java
.
A classpath is a list of locations to load classes from.
These 'locations' can either be directories, or jar files.
For directories, the JVM will follow an expected pattern for loading a class. If I have the directory C:/myproject/classes in my classpath, and I attempt to load a class com.mycompany.Foo, it will look under the classes directory for a directory called com, then under that a directory called mycompany, and finally it will look for a file called Foo.class in that directory.
In the second instance, for jar files, it will search the jar file for that class. A jar file is in reality just a zipped collection of directories like the above. If you unzip a jar file, you'll get a bunch of directories and class files following the pattern above.
So the JVM traverses a classpath from start to finish looking for the definition of the class when it attempts to load the class definition. For example, in the classpath :
C:/myproject/classes;C:/myproject/lib/stuff.jar;C:/myproject/lib/otherstuff.jar
The JVM will attempt to look in the directory classes first, then in stuff.jar and finally in otherstuff.jar.
When you get a ClassNotFoundException, it means the JVM has traversed the entire classpath and not found the class you've attempted to reference. The solution, as so often in the Java world, is to check your classpath.
You define a classpath on the command line by saying java -cp and then your classpath. In an IDE such as Eclipse, you'll have a menu option to specify your classpath.
If you know the path of the class or the jar containing the class then add it to your classpath while running it. You can use the classpath as mentioned here:
on Windows
java -classpath .;yourjar.jar YourMainClass
on UNIX/Linux
java -classpath .:yourjar.jar YourMainClass
Your classpath is broken (which is a very common problem in the Java world).
Depending on how you start your application, you need to revise the argument to -cp
, your Class-Path entry in MANIFEST.MF or your disk layout.