exceptions

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

In this tutorial we will discuss How to solve No Class Def Found Error (NoClassDefFoundError). This error is thrown when the Java Virtual Machine (JVM) or an instance of the ClassLoader class tries to load the definition of a class, but the definition could not be found. It extends the LinkageError class, which is used to indicate error cases, where a class has a dependency on some other class and that class has incompatibly changed after the compilation.

The definition of a class can be requested during a method call, or while creating a new instance using a new expression. Also, it is important to mention that the definition of the class existed when the application code was compiled, but the definition can no longer be found in the runtime.

Finally, the NoClassDefFoundError exists since the first version of Java.

The Structure of NoClassDefFoundError

Constructors

    • NoClassDefFoundError()

Creates an instance of the NoClassDefFoundError class.

    • NoClassDefFoundError(String s)

Creates an instance of the NoClassDefFoundError class, using the specified string as message.

The NoClassDefFoundError in Java

As we have already mentioned, the NoClassDefFoundError is thrown when the definition of class in not available during runtime. This error also indicates that the definition of the class was found during the compilation of the application, but it is not available in the application’s classpath during runtime. In general, this is a difficult error to deal with and through this tutorial, we will present a number of different solutions.

To begin with, let’s demonstrate an example that throws the aforementioned error. First, we define a Test class with a simple constructor:

Test.java:

public class Test {
        public Test() {
                System.out.println("A new instance of the Test class was created!");
        }
}

Then, we define a NoClassDefFoundErrorExample class that contains a static instance of the Test class:

NoClassDefFoundErrorExample.java:

public class NoClassDefFoundErrorExample {
        private static Test test = new Test();

        public static void main(String[] args) {
                System.out.println("The definition of Test was found!");
        }
}

The next step is to create an executable .jar file that shall execute the aforementioned main method. In order to achieve that, we first create a manifest file, called Manifest.txt and inside the file, we copy the following:

Main-Class: NoClassDefFoundErrorExample

Using the terminal (Linux or Mac) or the command prompt (Windows), we execute the following commands, in order to first, compile our source Java files and then, create our executable file:

javac Test.java
javac NoClassDefFoundErrorExample.java
jar cfm NoClassDefFoundErrorExample.jar Manifest.txt NoClassDefFoundErrorExample.class

Now, we are ready to execute our code using the following command:

java -jar NoClassDefFoundErrorExample.jar

A sample execution is shown below:

Exception in thread "main" java.lang.NoClassDefFoundError: TestClass
	at NoClassDefFoundErrorExample.(NoClassDefFoundErrorExample.java:2)
Caused by: java.lang.ClassNotFoundException: TestClass
	at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
	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

The NoClassDefFoundError was thrown because the definition of the Test class was not included in the application’s classpath. If we execute the following command:

jar cfm NoClassDefFoundErrorExample.jar Manifest.txt NoClassDefFoundErrorExample.class Test.class

and then, execute our code, we shall get the following output:

A new instance of the TestClass was created!
The definition of TestClass was found!

The NoClassDefFoundError during static initialization

The NoClassDefFoundError can also be thrown during the static initialization of a class. If an exception occurs during the loading and initialization of a class and the definition of another class depends on the former class, then an ExceptionInInitializerError is thrown.

The following class reproduces the aforementioned problem:

StaticInitializationErrorExample.java:

import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class StaticInitializationErrorExample {

	private final static int TOTAL_RECORDS = 100;

	public static void main(String args[]) {
		try{
			List records = new ArrayList(TOTAL_RECORDS);

			for(int i=1; i < TOTAL_RECORDS; ++i)
				records.add(new Record(i));
		}
		catch(Throwable t) {
			t.printStackTrace();
			throw t;
		}
	}
}

class Record {
	private static Integer ID = getRandomInteger();

	public Record(Integer Id){
		this.ID = Id;
	}

	private static Integer getRandomInteger() {
		throw new RuntimeException("The method is not implemented...");
		//return new Random.nextInt();
	}
}

In this example, we defined a Record class with a static field, called ID. When, the Record class is about to get loaded and initialized, the getRandomInteger() method throws a RuntimeException and thus, the main method that is static and requires the definition of the Record class throws an ExceptionInInitializerError.

A sample execution is shown below:

java.lang.ExceptionInInitializerError
	at StaticInitializationErrorExample.main(StaticInitializationErrorExample.java:14)
Caused by: java.lang.RuntimeException: The method is not implemented...
	at Record.getRandomInteger(StaticInitializationErrorExample.java:31)
	at Record.(StaticInitializationErrorExample.java:24)
	... 1 more
Exception in thread "main" java.lang.ExceptionInInitializerError
	at StaticInitializationErrorExample.main(StaticInitializationErrorExample.java:14)
Caused by: java.lang.RuntimeException: The method is not implemented...
	at Record.getRandomInteger(StaticInitializationErrorExample.java:31)
	at Record.(StaticInitializationErrorExample.java:24)
	... 1 more

How to deal with the NoClassDefFoundError

  • 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.
  • The classpath of the application is correct, but the Classpath environment variable is overridden before the application’s execution.
  • Verify that the aforementioned ExceptionInInitializerError does not appear in the stack trace of your application.

This was a tutorial on How to solve No Class Def Found Error (NoClassDefFoundError) in Java.

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Greg
Greg
6 years ago

The 2nd example is a bit confusing. You say NoClassDef… can be thrown if an exception is thrown, but it is actually a ExceptionInInitializerError which is definitively not a NoClassDefFound. I guess you wanted to phrase that a Linkage error can be thrown in this case, right ?

Vela Zikalala
Vela Zikalala
6 years ago

I have set the classpath on my computer but when I compile like this javac Test.java, it says javac is not recognised. I have jdk 10 installed. Please assist me here.

Back to top button