[java] How to solve java.lang.NoClassDefFoundError?

I've tried both the example 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 the graphics package (I added package graphics; to it), set the classpath to "_test" (folder containing graphics), compiled it, and ran it using java 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, but they have similar concepts.

This question is related to java exception packages noclassdeffounderror

The answer is


My two cents in this chain:

Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.


if you got one of these error 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)

-------------------------- SOLUTIION -----------------------

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]

I got this error after a Git branch change. For the specific case of Eclipse,there were missed lines on .settings directory for org.eclipse.wst.common.component file. As you can see below

Restoring the project dependencies with Maven Install would help.

enter image description here


I use the FileSync plugin for Eclipse so I can live debug on Tomcat & I received NoClassFoundError because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat but hadn't also added a folder sync for the extlib directory in Eclipse =>

C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib


If you are using more than one module, you should have

dexOptions {
    preDexLibraries = false
}

in your build file.


Check that if you have a static handler in your class. If so, please be careful, cause static handler only could be initiated in thread which has a looper, the crash could be triggered in this way:

1.firstly, create the instance of class in a simple thread and catch the crash.

2.then call the field method of Class in main thread, you will get the NoClassDefFoundError.

here is the test code:

public class MyClass{
       private static  Handler mHandler = new Handler();
       public static int num = 0;
}

in your onCrete method of Main activity, add test code part:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //test code start
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                MyClass myClass = new MyClass();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }).start();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    MyClass.num = 3;
    // end of test code
}

there is a simple way to fix it using a handlerThread to init handler:

private static Handler mHandler;
private static HandlerThread handlerThread = new HandlerThread("newthread");
static {
    handlerThread.start();
    mHandler = new Handler(handlerThread.getLooper(), mHandlerCB);
}

Don't use test classes outside the module

I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.

I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.

My solution was to place the method in a existing utilities class that is part of the production code.


It happens a lot with my genymotion devices. Make sure you have a good amount of memory available on your drive where Genymotion is installed.


One source of error for this exception could stem from inconsistent definitions for Proguard, e.g. a missing

-libraryJars "path.to.a.missing.jar.library".

This explains why compilation and running works fine, given that the jar is there, while clean & build fails. Remember to define newly added jar libraries in proguard setup!

Note that error messages from Proguard are really not up to standard, as they are easily confused with similar ant messages arriving when the jar is not there at all. Only at the very bottom will there be a small hint of proguard in trouble. Hence, it is quite logic to start searching for traditional classpath errors etc, but this will be in vain.

Evidently, the NoClassDefFound exception will be the results when running e.g. the resulting executable jar built and based on a lack of proguard consistency. Some call it proguard "Hell"


This answer is specific to a java.lang.NoClassDefFoundError happening in a service:

My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.

However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.

The eventual solution: Restart the service!

It appears that the rpm upgrade invalidated the service's file handle on the underlying jar file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.

Hope that specific case helps someone.


if you are using gradlew, go to ./gradle/wrapper/gradle-wrapper.properties and change distributionUrl to the correct version of gradle.

If you are using JDK14 try

distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip

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.


I had the same issue with my Android development using Android studio. Solutions provided are general and did not help me ( at least for me). After hours of research I found following solution and may help to android developers who are doing development using android studio. modify the setting as below Preferences ->Build, Execution, Deployment -> Instant Run -> un-check the first option.

With this change I am up and running. Hope this will help my dev friends.


I have faced with the problem today. I have an Android project and after enabling multidex the project wouldn't start anymore.

The reason was that I had forgotten to call the specific multidex method that should be added to the Application class and invoked before everything else.

 MultiDex.install(this);

Follow this tutorial to enable multidex correctly. https://developer.android.com/studio/build/multidex.html

You should add these lines to your Application class

 @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }

For my project, what solved the issue was that Chrome browser and chromedriver were not compatibles. I had a very old version of the driver that could not even open the browser. I just downloaded the latest version of both and problem solved. How did I discovered the issue? Because I ran my project using the Selenium native firefox driver with an old version of FF inculded with my application, I realized then that the problem was incompatibility of between browser and driver.

Hope this can help anyone with a similiar issue as mine, that generated this same Error Message.


This error means you didn't add some of dependencies.


After working on a NetBeans project for many months, I suddenly got the NoClassDefFoundError message shortly after getting a "Low Memory" alert. Doing a Clean rebuild didn't help, but closing Netbeans altogether and reopening the project there were no error reports.


If your project is in a package like com.blahcode and your class is called Main, the compiled files may be output in a directory structure like ./out/com/blahcode/Main.class. This is especially true for IntelliJ IDEA.

When trying to run from a shell or cmd, you need to cd to that which contains com as a sub-directory.

cd out
java -classpath . com.blahcode.Main

I'd like to correct the perspective of others on NoClassDefFoundError.

NoClassDefFoundError can occur for multiple reasons like

  1. ClassNotFoundException -- .class not found for that referenced class irrespective of whether it is available at compile time or not(i.e base/child class).
  2. Class file located, but Exception raised while initializing static variables
  3. 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 it means by saying "available in compile time"?

  • The referenced class is used in the code.
    Eg: 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 it means 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")
    Eg: Two classes, A and B(extends A). Code has
    A a = Class.forName("B").newInstance();

No Class Definition Exception occurs when the intended class is not found in the Class Path. At Compile Time Class : Class was generated from Java Compiler, But Somehow at Run Time the Dependent Class is not found.

Lets go through one Simple Example :

public class ClassA{
public static void main(String args[]){
     //Some gibberish Code...
     String text = ClassB.getString();
     System.out.println("Text is :" + text);
}

}

public class ClassB{
    public static String getString(){
      return "Testing Some Exception";
 }
}

Now Lets assume that the above two Java Source Code are placed in some Folder let say "NoClassDefinationFoundExceptionDemo"

Now open a shell(Assuming Java is already being setup correctly)

  1. Go to Folder "NoClassDefinationFoundExceptionDemo"
  2. Compile Java Source Files javac ClassB javac ClassA
  3. Both Files are Compiled Sucessfully and generated Class files in the same Folder as ClassA.class and ClassB.class
  4. Now Since we are overiding ClassPath to current working directory therefore we execute the following command java -cp . ClassA and It worked Successfully and you will see the Output in the screen
  5. Now Lets say, You removed ClassB.class file from Present Directory. and now you execute the command again. java -cp . ClassA Now it will greet you with NoClassDefFoundException. as ClassB which is a dependency for ClassA is not found in the classpath(i.e present working directory).

For Meteor or Cordova users,

It can be caused by the Java version you use, for meteor and cordova stick with version 8 for now.

1- Check available Java versions /usr/libexec/java_home -V and look for the path name for Java version 8

2- Set the path for Java version 8
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home

3- Check if it is done echo $JAVA_HOME

Go on and contiune coding.


I'm developing an Eclipse based application also known as RCP (Rich Client Platform). And I have been facing this problem after refactoring (moving one class from an plugIn to a new one).

Cleaning the project and Maven update didn't help.

The problem was caused by the Bundle-Activator which haven't been updated automatically. Manual update of the Bundle-Activator under MANIFEST.MF in the new PlugIn has fixed my problem.


if you recently added multidex support in android studio like this:

// To Support MultiDex
implementation 'com.android.support:multidex:1.0.1'

so your solution is just extend From MultiDexApplication instead of Application

public class MyApp extends MultiDexApplication {

NoClassDefFoundError in Java:

Definition:

NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError: Exception in thread "main" java.lang.NoClassDefFoundError

Possible Causes:

  1. The class is not available in Java Classpath.

  2. You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.

  3. Any start-up script is overriding Classpath environment variable.

  4. Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.

  5. Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.

  6. If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.

Possible Resolutions:

  1. Verify that all required Java classes are included in the application’s classpath. The most common mistake is not to include all the necessary classes, before starting to execute a Java application that has dependencies on some external libraries.

  2. The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.

  3. Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.

Resources:

3 ways to solve java.lang.NoClassDefFoundError in Java J2EE

java.lang.NoClassDefFoundError – How to solve No Class Def Found Error


I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.

Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'

It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.

// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5

import java.lang.instrument.*;
import java.security.*;

// manifest.mf
// Premain-Class: ClassLoadTracer

// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class

// java -javaagent:tracer.jar  [...]

public class ClassLoadTracer 
{
    public static void premain(String agentArgs, Instrumentation inst) 
    {
        final java.io.PrintStream out = System.out;
        inst.addTransformer(new ClassFileTransformer() {
            public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

                String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
                out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);

                // dump stack trace of the thread loading class 
                Thread.dumpStack();

                // we just want the original .class bytes to be loaded!
                // we are not instrumenting it...
                return null;
            }
        });
    }
}

It happened to me in Android Studio.

The solution that worked for me: just restart the studio.


java.lang.NoClassDefFoundError

indicates, that something was found at compiletime but not at runtime. maybe you just have to add it to the classpath.


In my environment, I encounter this issue in unit test. After appending one library dependency to *.pom, that's fixed.

e.g.:

error message:

java.lang.NoClassDefFoundError: com/abc/def/foo/xyz/Iottt

pom:

<dependency>
    <groupId>com.abc.def</groupId>
    <artifactId>foo</artifactId>
    <scope>test</scope>
</dependency>

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to packages

How to install Python packages from the tar.gz file without using pip install Package name does not correspond to the file path - IntelliJ Can I force pip to reinstall the current version? The import android.support cannot be resolved How to solve java.lang.NoClassDefFoundError? How to list all installed packages and their versions in Python? Importing packages in Java Check for installed packages before running install.packages() How do I find a list of Homebrew's installable packages? Installing a local module using npm?

Examples related to noclassdeffounderror

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory How to solve java.lang.NoClassDefFoundError? setting JAVA_HOME & CLASSPATH in CentOS 6 java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing Unable instantiate android.gms.maps.MapFragment Android java.lang.NoClassDefFoundError NoClassDefFoundError for code in an Java library on Android java.lang.NoClassDefFoundError: Could not initialize class XXX exception in thread 'main' java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError in junit