How do I resolve ClassNotFoundException?
Asked Answered
B

30

164

I am trying to run a Java application, but getting this error:

java.lang.ClassNotFoundException:

After the colon comes the location of the class that is missing. However, I know that that location does not exist since the class is located elsewhere. How can I update the path of that class? Does it have something to do with the class path?

Bridgeport answered 1/7, 2013 at 15:58 Comment(5)
You must add the jar which has the missing class to the classptahCrib
if your class has a package then go to the folder containing the class. e.g if package is package test.abc, then go to folder before test and then do java -cp . test.abc.CLASSNAME (without .class). If there's no package then go to folder containing class and say java -cp . CLASSNAMECheslie
Either a class was not deployed to your runtime (for example missing jar), or the class is not visible in a given class loader, check this this tool that helps troubleshooting these problems: jhades.orgSusannasusannah
I also run into this sometimes. This exception clearly violates the rule of stating all necessary context in an exception message. It should mention where it tried to look for the thing, what is on your classpath. Please make better exception messages. Don't make us hunt for information which could help solve the problem.Aultman
I don't know if you make the same stupid mistake as I did, but instead of java ClassName.class, run 'java ClassName'. Sometimes auto-complete gives you .\ClassName, remove that .\ as wellGlamorize
T
46

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.

Thereabout answered 1/7, 2013 at 16:2 Comment(10)
Can you please be more eclipse specific? What do I have to do?Bridgeport
Your question does not contain enough information to provide a more specfiic answer. Consider adding that.Issuable
Dependency resolution/version mismatches is a very common problem in basically all programming environments. We could say that all any program ever does is resolve such definitions... the question is always what/where is the definition and which version did you mean?Aultman
I am just emphasizing that besides the Java world all of software has a fight with ensuring that correct versions of dependencies are found. I can mention dll-hell, package managers, version managers, spring boot bill of materials and docker containers as examples of this problem and possible solutions. The larger the fraction of foreign code becones the larger the problem gets.Aultman
@Aultman Yes, but that is not necessarily the problem here and you may be barking up the wrong tree. All that can be said is that the classpath is broken.Issuable
You don't give anyway to print out the classpath. Don't give anyway to print out class name that's not found.Edik
If you understand how this works, please help others by explaining it. Your answer brings me no closer to a solution. I have repeatedly hit these problems, and have spend several times as many hours resolving dependency and class path related issues as hours spent actually coding. Java is by far the most broken tool chain and this is a real nightmare for anyone trying to get up to speed.Roeser
@Roeser The Java classpath is probably the first non-trivial thing not part of the Java language as you read it, that everyone runs into problems with and you absolutely need to understand in order to progress. This old answer cannot say what is wrong (and hence how to fix it) because the question does not contain enough information. Consider opening a new question carefully explaining your problem.Issuable
The problem for new adopters is that you are dumped into a place where you have no clue how to move forward. I typical scenario is: go to the getting started guide for some shared library, copy/paste a few lines into pom.xml, copy/paste a trivial example into your code. My code compiles but when I run it throws ClassNotFoundException, and at this point I have no clue where to begin to figure out why. Telling me that my classpath is broken is completely unhelpful, since I didn't do anything related to class paths, I just installed IntelliJ and followed a trivially simple getting started.Roeser
@Roeser You are complaining that this decade old answer saying explicitly what is broken, and that OP did not provide enough information for a better answer, is not useful to you with a most likely completely different problem. Well, sorry about that. Many better answers to better questions exist on this site. I will again recommend you to open your own question explaining exactly what your problem is, because that will most likely give you an answer suitable for where you are now.Issuable
C
68

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.

Clueless answered 1/7, 2013 at 16:20 Comment(0)
T
46

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.

Thereabout answered 1/7, 2013 at 16:2 Comment(10)
Can you please be more eclipse specific? What do I have to do?Bridgeport
Your question does not contain enough information to provide a more specfiic answer. Consider adding that.Issuable
Dependency resolution/version mismatches is a very common problem in basically all programming environments. We could say that all any program ever does is resolve such definitions... the question is always what/where is the definition and which version did you mean?Aultman
I am just emphasizing that besides the Java world all of software has a fight with ensuring that correct versions of dependencies are found. I can mention dll-hell, package managers, version managers, spring boot bill of materials and docker containers as examples of this problem and possible solutions. The larger the fraction of foreign code becones the larger the problem gets.Aultman
@Aultman Yes, but that is not necessarily the problem here and you may be barking up the wrong tree. All that can be said is that the classpath is broken.Issuable
You don't give anyway to print out the classpath. Don't give anyway to print out class name that's not found.Edik
If you understand how this works, please help others by explaining it. Your answer brings me no closer to a solution. I have repeatedly hit these problems, and have spend several times as many hours resolving dependency and class path related issues as hours spent actually coding. Java is by far the most broken tool chain and this is a real nightmare for anyone trying to get up to speed.Roeser
@Roeser The Java classpath is probably the first non-trivial thing not part of the Java language as you read it, that everyone runs into problems with and you absolutely need to understand in order to progress. This old answer cannot say what is wrong (and hence how to fix it) because the question does not contain enough information. Consider opening a new question carefully explaining your problem.Issuable
The problem for new adopters is that you are dumped into a place where you have no clue how to move forward. I typical scenario is: go to the getting started guide for some shared library, copy/paste a few lines into pom.xml, copy/paste a trivial example into your code. My code compiles but when I run it throws ClassNotFoundException, and at this point I have no clue where to begin to figure out why. Telling me that my classpath is broken is completely unhelpful, since I didn't do anything related to class paths, I just installed IntelliJ and followed a trivially simple getting started.Roeser
@Roeser You are complaining that this decade old answer saying explicitly what is broken, and that OP did not provide enough information for a better answer, is not useful to you with a most likely completely different problem. Well, sorry about that. Many better answers to better questions exist on this site. I will again recommend you to open your own question explaining exactly what your problem is, because that will most likely give you an answer suitable for where you are now.Issuable
Z
24

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: enter image description here

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: enter image description here

NOTE: You have to execute the above java command no matter what your current location is. But this is not the case for javac. For compiling you can even directly go into the directory where you have your .java files and directly execute javac ClassName.java.

Zeeland answered 5/10, 2015 at 6:44 Comment(0)
T
11

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
Tuckie answered 1/7, 2013 at 16:0 Comment(0)
M
11

I had the same error and it took me a whole day to realize it's a dependency conflict issue:

  • I imported two libraries, A and B;
  • Both A and B depends on another library C, but different versions of C. Let's say A depends on C 1.0 and B depends on C 2.0;
  • B makes use of a class that only exists in C 2.0;
  • However, A is "closer" in the dependency tree, so Maven uses C 1.0 for both A and B and doesn't even warn you about this (it's quite astounding to me);
  • As a result, when B tries to use the class that only exists in C 2.0, a ClassNotFoundException is thrown;

Now the weird thing is: if you navigate the code of B in your IDE and try to jump to the class that only exists in C 2.0, it works correctly. C 2.0 is indeed installed and your IDE knows about it, but it's just ignored when running the application.

This really drove me mad...

I ended up having to add C 2.0 to my pom.xml so that it can be chosen over C 1.0.

Please refer to this post for how Maven chooses the closest dependency: https://mcmap.net/q/151686/-can-multiple-versions-of-the-same-dependency-be-used-in-a-single-maven-repository

You can use mvn dependency:tree to visualize the dependency tree.

Mosely answered 7/11, 2021 at 15:36 Comment(1)
Most useful answer so far, because it explains a common real life situation well, instead of just parrotting "check your classpath", as most other answers do.Sarette
G
5

Basic Generic Question - Simplest Generic Answer ;)

Given the information I will make the assumption that you might be trying a basic approach to coding, building/compiling and running a simple console app like "Hello World", using some simple text editor and some Command Shell.

This error occurs in the following scenario:

..\SomePath>javac HelloWorld.java
..\SomePath>java HelloWorld.class

In other words, use:

..\SomePath>java HelloWorld

P.S. The addition to the file extension .class produces the same mistake. Also, be sure to have the Java's (JDK/JRE) bin folder in the operating system's Environment Variable's PATH.
P.P.S. Was I correct in my assumption/s?

Galilean answered 13/2, 2019 at 18:43 Comment(0)
O
4

Try these if you use maven. I use maven for my project and when I do mvn clean install and try to run a program it throws the exception. So, I clean the project and run it again and it works for me.

I use eclipse IDE.

For Class Not Found Exception when running Junit test, try running mvn clean test once. It will compile all the test classes.

Oecd answered 22/4, 2015 at 19:48 Comment(2)
what directory were you in when you ran "mvn clean test"? is it in the same directory as the POM?Ommatidium
Yes. Ran it from the directory where pom file is present.Oecd
H
4

Add the full path of jar file to the CLASSPATH. In linux use: export CLASSPATH=".:/full/path/to/file.jar:$CLASSPATH". Other way worked (without editing the CLASSPATH) was unzipping the jar in the current project folder.

Ways didn't work for me:

1) Using -cp option with full path of jar file.

2) Using -cpwith only the name of jar when located in the current folder

3) Copying the jar to the current project folder

4) Copying the jar to standard location of java jars (/usr/share/java)

This solution is reported for class com.mysql.jdbc.Driver in mysql-connector-java.5-*.jar, working on linux with OpenJDK version 1.7

Hutcheson answered 4/12, 2015 at 9:5 Comment(1)
Only unzipping the JAR worked for me, none of the other solutions didVerger
M
4

If you use maven, check that you have this plugin in your pom.xml:

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Attach the shade goal into the package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

It will put your dependency (the exception reason) to your jar.

FYI: this will include all dependencies inflated in the final jar

Mcbrayer answered 13/12, 2019 at 13:33 Comment(0)
C
3

To add the location of a class to your classpath via command line simply add -cp or -classpath and the location of the class while running it. I.E.

java -cp "c:/location/of/file" YourProgram

Or if you're running an IDE such as eclipse you can right click on the project -> build path -> configure build path and add the external JAR containing your class to the build path then it should work fine.

Caralie answered 1/7, 2013 at 16:5 Comment(0)
B
3

Use ';' as the separator. If your environment variables are set correctly, you should see your settings. If your PATH and CLASSPATH is correct, windows should recognize those commands. You do NOT need to restart your computer when installing Java.

Basilica answered 19/1, 2015 at 8:33 Comment(1)
That is on windows (semicolon) , on unix/linux it is ':' (colon)Utrillo
F
3

This can happen on Windows after a java update where the old version of the java SDK is missing and a new one is present. I would check if your IDE is using the installed java SDK version (IntelliJ: CTRL + SHIFT + ALT + S)

Falbala answered 3/4, 2018 at 14:3 Comment(0)
C
2

Go up to the top and remove the import statement if there is one, and re import the class. But if that isn't the case do a clean then build. Are you using Netbeans or Eclipse?

Costume answered 1/7, 2013 at 16:4 Comment(0)
W
2

I ran into this as well and tried all of the other solutions. I did not have the .class file in my HTML folder, I only had the .java file. Once I added the .class file the program worked fine.

Welldressed answered 13/1, 2014 at 15:35 Comment(0)
T
2
  1. It could happen if your classpath is not correct

  2. Let us posit a serializable class and deserializable class under same projectname. You run the serializable class, creating a serializable object in specific folder. Now you need the desearialized data. In the meantime, if you change the name of the project it will not work. You have to run the serializable class first and then deserialize the file.

Towel answered 10/2, 2014 at 22:5 Comment(0)
G
2

If you are using maven try to maven update all projects and force for snapshots. It will clean as well and rebuilt all classpath.. It solved my problem..

Galleon answered 11/1, 2017 at 8:16 Comment(0)
E
2

I just did

1.Invalidate caches and restart

2.Rebuilt my project which solved the problem

Efface answered 19/2, 2018 at 11:27 Comment(0)
R
2

It's worth noting that sometimes Java lies about the Class that is causing the problem.

You can get this error if java tries to load class A which depends on class B and class B can't be loaded.

In some circumstances java reports that class A can't be loaded when the problem is B.

From recollection the last time this occurred was when class A includes a static field or a static initializer that loaded class B.

So after checking your class path is correct (I actually dump the full classpath on startup) I then do a binary chop on class A.

By this I mean, I remove half of the code in A.

If it still fails I remove another half and so on until the problem (hopefully goes away).

Reunite answered 18/11, 2021 at 3:41 Comment(0)
L
1

I was trying to run .jar from C# code using Process class. The java code ran successfully from eclipse but it doesn't from C# visual studio and even clicking directly on the jar file, it always stopped with ClassNotFoundException: exception. Solution for my, was export the java program as "Runnable JAR file" instead of "JAR File". Hope it can help someone.

Lorikeet answered 14/2, 2018 at 13:24 Comment(0)
S
0

If you have added multiple (Third-Party)**libraries and Extends **Application class

Then it might occur.

For that, you have to set multiDexEnabled true and replace your extended Application class with MultiDexApplication.

It will be solved.

Shaughnessy answered 22/9, 2018 at 9:41 Comment(0)
A
0

In my case the class thrown as class not found exception has properties related to ssl certificates. Close the eclipse and open with as “Run as Administrator” then issue got resolved. As eclipse have issue related permission it will throw such kind of exception.

Ammonate answered 13/2, 2020 at 6:16 Comment(0)
C
0

I started having this issue after upgrading the "Java Language Support" plugin from Visual Studio Code from version 0.66.0 to 0.67.0.

Downgrading back allowed me to run the same code without any issue.

Caspian answered 27/9, 2020 at 4:29 Comment(0)
W
0

If you have moved your project to new machine or importing it from git, then try this.

  1. Right Click on class > Run as > Run Configuration
  2. remove main class reference
  3. Apply > Close
  4. Now again right click on class > run as java application.

It worked for me.

Wimsatt answered 3/11, 2020 at 9:56 Comment(0)
D
0

I ran the Java code at the Terminal and adding Class Path was solution like this:
> java -cp <JAR file> <JAVA Class file>
for example, c:\code\prototype-app\target\classes>java -cp ..\prototype-app-1.0-SNAPSHOT.jar com_stree.app.DetectLabels

My runtime environment:
  OS: Windows 10
  JAVA: 15.0.1
  Maven: 3.8.1

Dysphemism answered 19/7, 2021 at 18:10 Comment(0)
R
0

Check the .jar or .class file permissions. I had the jar on a project library with permission of -rw-r--r-- and I changed it to -rw-rw-r-- using on Linux:

chmod 664 <.jar>

One library was calling ClassLoader.loadClass which started the error when loading the class in the jar with wrong permission.

Rigger answered 4/1, 2023 at 13:18 Comment(0)
F
0

On my case, I´m using Spring Tool Suite 4, and my problem was solved doing that two steps:

  1. Right Click on the project --> Run As --> Maven clean.
  2. Right Click on the project --> Run As --> Maven install.

Then I could run the project with: Run As --> Spring Boot App.

Hope It helps someone :)

Florri answered 21/3, 2023 at 20:56 Comment(0)
I
0

Passing the package name is the key and classname along with the jar file, After running the mvn package command.

Run the following by modifying the Jar and package name as per below.

java -cp target\Test-1.0-SNAPSHOT.jar com.compname.Test

Indomitability answered 19/12, 2023 at 19:44 Comment(0)
A
-2

I deleted some unused imports and it fixed the problem for me. You can't not find a Class if you never look for it in the first place.

Amphitryon answered 5/2, 2021 at 10:37 Comment(5)
Deleting unused imports will not fix a ClassNotFoundException. Unused imports have zero impact at runtime. You must have done something else as well ... and that fixed the problem.Danie
@StephenC I know what I saw. An unused import may have no impact at runtime, but what about compile time, huh?Amphitryon
Then they weren't unused. They were used ... in the wrong way! For example, if you import a class with the same name as some other class that would have been default imported (e.g. a class in the current package or in java.lang) then deleting the import changes the program, and possibly fixes compile time or even runtime issues. But NOT a ClassNotFoundException ... which is what this question is about.Danie
(If you know what you saw ... reproduce it, and show us the evidence.)Danie
Actually ... I guess it could fix a ClassNotFoundException if you have imports that hide the correct classes, AND your compile and runtime classpaths are different. But you would have to make a number of different mistakes to achieve this.Danie
C
-2

sorry i am late to the question, but i will explain it to you in the simplest layman language. When you type 'javac <programname.java> The compiler checks the program and finds errors, first of all make sure your program is in the same directory as you have executed in the command prompt. Then it creates a. Class file of your program. For ex. If the name of my program was Test.java then the class file created should be Test.class which will be executed in the next line. Sometimes java takes some other name for your .class, use that name and voila you'll get the output.

Civilized answered 22/2, 2021 at 7:52 Comment(0)
E
-11

Put all the code in try block then catch exception in a catch block

try
{
    // code
}
catch(ClassNotFoundException e1)
{
    e1.getmessage();
}
Epexegesis answered 23/2, 2015 at 15:53 Comment(1)
This does not resolve the exception. This hides the exception. Furthermore, "e1.getmessage()" is a) the wrong capitalisation of getMessage() and b) not going to do very much as it returns a string with a message and you're not printing it or logging it or anything!Sloth

© 2022 - 2024 — McMap. All rights reserved.