How can I solve "java.lang.NoClassDefFoundError"?
Solution 1
After you compile your code, you end up with .class
files for each class in your program. These binary files are the bytecode that Java interprets to execute your program. The NoClassDefFoundError
indicates that the classloader (in this case java.net.URLClassLoader
), which is responsible for dynamically loading classes, cannot find the .class
file for the class that you're trying to use.
Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader
) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError
can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.
For example, if you had a class com.example.Foo
, after compiling you would have a class file Foo.class
. Say for example your working directory is .../project/
. That class file must be placed in .../project/com/example
, and you would set your classpath to .../project/
.
Side note: I would recommend taking advantage of the amazing tooling that exists for Java and JVM languages. Modern IDEs like Eclipse and IntelliJ IDEA and build management tools like Maven or Gradle will help you not have to worry about classpaths (as much) and focus on the code! That said, this link explains how to set the classpath when you execute on the command line.
Solution 2
I'd like to correct the perspective of others on NoClassDefFoundError
.
NoClassDefFoundError
can occur for multiple reasons like:
- ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
- Class file located, but Exception raised while initializing static variables
- Class file located, Exception raised while initializing static blocks
In the original question, it was the first case which can be corrected by setting CLASSPATH to the referenced classes JAR file or to its package folder.
What does it mean by saying "available in compile time"?
- The referenced class is used in the code.
E.g.: Two classes, A and B (extends A). If B is referenced directly in the code, it is available at compile time, i.e.,A a = new B();
What does it mean by saying "not available at compile time"?
- The compile time class and runtime class are different, i.e., for example base class is loaded using classname of child class for example
Class.forName("classname")
E.g.: Two classes, A and B (extends A). Code has
A a = Class.forName("B").newInstance();
Solution 3
NoClassDefFoundError
means that the class is present in the classpath at Compile time
, but it doesn't exist in the classpath at Runtime
.
If you're using Eclipse, make sure you have the shapes
, linepoints
and the spaceobjects
as entries in the .classpath
file.
Solution 4
If you got one of these errors while compiling and running:
NoClassDefFoundError
Error: Could not find or load main class hello
Exception in thread "main" java.lang.NoClassDefFoundError:javaTest/test/hello (wrong name: test/hello)
at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
-------------------------- Solution -----------------------
The problem is mostly in packages organization. You should arrange your classes in folders properly regarding to the package classifications in your source code.
On compiling process, use this command:
javac -d . [FileName.java]
To run the class, please use this command:
java [Package].[ClassName]
Solution 5
java.lang.NoClassDefFoundError
indicates that something was found at compile time, but not at run time. Maybe you just have to add it to the classpath.
Related videos on Youtube
Comments
-
Jonathan Lam almost 2 years
I've tried both the examples in Oracle's Java Tutorials. They both compile fine, but at run time, both come up with this error:
Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square at Main.main(Main.java:7) Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 1 more
I think I might have the
Main.java
file in the wrong folder.Here is the directory hierarchy:
graphics ├ Main.java ├ shapes | ├ Square.java | ├ Triangle.java ├ linepoint | ├ Line.java | ├ Point.java ├ spaceobjects | ├ Cube.java | ├ RectPrism.java
And here is
Main.java
:import graphics.shapes.*; import graphics.linepoint.* import graphics.spaceobjects.*; public class Main { public static void main(String args[]) { Square s = new Square(2, 3, 15); Line l = new Line(1, 5, 2, 3); Cube c = new Cube(13, 32, 22); } }
What am I doing wrong here?
UPDATE
After I put put the
Main
class into thegraphics
package (I addedpackage graphics;
to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it usingjava graphics.Main
(from the command line), it worked.Really late UPDATE #2
I wasn't using Eclipse (just Notepad++ and the JDK), and the above update solved my problem. However, it seems that many of these answers are for Eclipse and IntelliJ IDEA, but they have similar concepts.
-
lreeder almost 11 yearsLooking at your main class, it is not in a package (you would have
package graphics;
at the top). Isgraphics
the head of your package structure? Does Square havepackage graphics.shapes
at the top? -
Thor84no almost 11 yearsYou're listing where the .java files are, but since what you're getting is a runtime issue, what you're actually interested in is where the .class files are and whether they are on your classpath or not. How are you executing the Main class?
-
happybuddha almost 11 yearsJust hit Shift+ctrl+o in eclipse to organize your imports
-
Jeremy Borg about 10 yearsMake sure that you type the class name correctly. I was getting this error because I didn't start the class name with an upper case letter
-
Zar about 10 yearsThis sometimes occur in IntelliJ IDEA after a major refactoring. Right click on your project and select -> Compile Module, and then re-start the project and it should work again.
-
Vaishali Kulkarni over 9 yearsIf you are getting NoClassDefFoundError for some external jar file that you have added to the project, try adding the jar file in lib folder and add it to the classpath by Properties >> Java Build Path >> Add Variable >> Configure Variables >> New Variable Entry. And rebuild.
-
Jel almost 7 yearsI encountered this problem when working with Apache Axis. Spent hours messing with the classpath/build configuration based on most of the feedback here and in similar threads. Turns out I was missing the necessary supporting XML libraries for certain web service transactions. Added them to the project and all became well
-
wei over 6 yearsFor NetBeans user, you can try to click
Clean and Build Project
This worked for me. -
Dani Aya about 6 yearsIf you (like me) were trying several solutions and spent hours without a progress, please notice that eclipse has two different options to export your project into jar executables, which are: Jar file and Runnable Jar File. I exported selecting Runnable Jar File and that does the trick.
-
ibrahimgunes about 6 yearsI had this error when I was opening a page that used apache poi library. I remove it's folder from .m2 repository folder then I updated my project. Basically hitting maven>update project. It worked. I hope it helps
-
-
taco over 9 yearsIn my case, I had compiled a class, them moved it to a directory called app. I had to add a line with
package app;
and recompile before I could move it into the subdirectory app. -
Fahad over 8 yearsApart from above listed 3, ClassLoaders also may cause the such error, which is basically ClassNotFoundException, in this scenario class may present in classpath but attempt to load from different ClassLoader
-
Wai Ha Lee over 8 yearsDo you have any reference for that?
-
totteire over 8 yearsNop, I just run out of disk space regularly and unless I free a good amount + remove/reinstall a Genymotion virtual device I keep getting this error.
-
Samuel about 8 years2 and 3 are classloader-specific. According to the javadoc, the exception is only intended for reason 1.
-
p1nkrock almost 8 years@Samuel Leave about javadoc. please go ahead with a sample program to find the reasons.
-
sschrass over 7 yearsdepends on the context you are asking for.
-
Michael over 7 yearsI have tested the case 2 and case 3, it' not NoClassDefFoundError, it's ExceptionInInitializerError Case 2.Class file located, but Exception raised while initializing static variables Case 3.Class file located, Exception raised while initializing static blocks
-
Maveňツ about 7 yearsHow to handle that in runtime via try/catch?
-
Elmue about 7 yearsThis answer is not correct the way you write it. Correct would be: "ONE possible cause of this error is...." But there may be other reasons why you get this error for example when loading a JAR file at runtime with a classloader.
-
Pacerier over 6 years@Michael, This link says that your stacktrace will too show
NoClassDefFoundError
for that case: archive.is/YPbYI#selection-2107.0-2115.13 -
Stephen C about 5 yearsThis is true in part, but it is more complicated. 1) You can use relative paths in the classpath, but they must be resolvable by the JVM ... relative to the JVM's current directory. This makes them fragile. 2) You can use
~
and other shell meta characters when setting a classpath environment variable, but only provided the mechanism you are using to set the variable expands them to real pathnames. If you are usingbash
, you can get "mixed" results. For example, look at what you get when you typeecho ~:~
on the command line. The first~
is expanded, but the second isn't. -
Jorge Sampayo almost 5 yearsThe "-d ." in javac command does the trick, creating the folder structure of the packages instead of putting all the .class files on the root directory, thanks!
-
danmaze almost 4 yearsI'm reading this because of an error I encountered while trying to run a unit test on Android. It turns out that the NoClassDefFoundError, in my case, occurred as a result of missing dependencies in the test. I need to think about dependency injection to prevent errors like this. Thanks for the elaborate answer.
-
Peter Mortensen almost 3 yearsWhat is "rpm"? Is it related to package management on Red Hat Linux? Or something else?
-
John Chesshir almost 3 years@PeterMortensen It stands for Red Hat Package Manager, although recently they've employed recursive naming to call it just RPM Package Manager.
-
Camilo Acevedo. over 2 yearsThank you, Sr. That solves the error for compiling.
-
bunkinet over 2 yearsI got this error due to setting FormLayout(JGoodies) for layout setting of a Form. Which means there are issues with that class library to be fixed. Yet it appears in layout list of a Form in IntelliJ.
-
Spodgy over 2 yearsWas searching a solution for a similar error and case 2 was the problem - thanks!
-
suleimanforever almost 2 yearsDon't forget to like and subscribe, wait this isn't Youtube...