How do I resolve ClassNotFoundException?

前端 未结 22 1466
后悔当初
后悔当初 2020-11-21 06:06

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

java.lang.ClassNotFoundException:

After the colon comes the location of the cla

相关标签:
22条回答
  • 2020-11-21 06:47

    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.

    0 讨论(0)
  • 2020-11-21 06:48

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

    try
    {
        // code
    }
    catch(ClassNotFoundException e1)
    {
        e1.getmessage();
    }
    
    0 讨论(0)
  • 2020-11-21 06:49

    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.

    0 讨论(0)
  • 2020-11-21 06:49

    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.

    0 讨论(0)
提交回复
热议问题