How do I resolve ClassNotFoundException?

814,961

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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

Solution 5

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

Share:
814,961
user2426316
Author by

user2426316

Updated on July 08, 2022

Comments

  • user2426316
    user2426316 almost 2 years

    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?

    • Crom
      Crom almost 11 years
      You must add the jar which has the missing class to the classptah
    • Optional
      Optional almost 11 years
      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 . CLASSNAME
    • Angular University
      Angular University over 10 years
      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.org
    • masterxilo
      masterxilo over 5 years
      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.
  • user2426316
    user2426316 almost 11 years
    Can you please be more eclipse specific? What do I have to do?
  • matbrgz
    matbrgz almost 11 years
    Your question does not contain enough information to provide a more specfiic answer. Consider adding that.
  • Joeblade
    Joeblade over 9 years
    That is on windows (semicolon) , on unix/linux it is ':' (colon)
  • OverCoder
    OverCoder almost 8 years
    Only unzipping the JAR worked for me, none of the other solutions did
  • IBBoard
    IBBoard over 7 years
    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!
  • TacoB0t
    TacoB0t about 6 years
    what directory were you in when you ran "mvn clean test"? is it in the same directory as the POM?
  • Arun
    Arun about 6 years
    Yes. Ran it from the directory where pom file is present.
  • masterxilo
    masterxilo over 5 years
    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?
  • masterxilo
    masterxilo over 5 years
    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.
  • matbrgz
    matbrgz over 5 years
    @masterxilo 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.
  • Stephen C
    Stephen C almost 3 years
    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.
  • Funny Geeks
    Funny Geeks over 2 years
    @StephenC I know what I saw. An unused import may have no impact at runtime, but what about compile time, huh?
  • Stephen C
    Stephen C over 2 years
    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.
  • Stephen C
    Stephen C over 2 years
    (If you know what you saw ... reproduce it, and show us the evidence.)
  • Stephen C
    Stephen C over 2 years
    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.
  • Philip Rego
    Philip Rego about 2 years
    You don't give anyway to print out the classpath. Don't give anyway to print out class name that's not found.
  • bikeman868
    bikeman868 almost 2 years
    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.
  • matbrgz
    matbrgz almost 2 years
    @bikeman868 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.
  • bikeman868
    bikeman868 almost 2 years
    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.
  • matbrgz
    matbrgz almost 2 years
    @bikeman868 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.