Core Java

java.lang.NoClassDefFoundError: How to resolve – Part 2

This article is part 2 of our NoClassDefFoundError troubleshooting series. Take a look at part 1. It will focus and describe the simplest type of NoClassDefFoundError problem. This article is ideal for Java beginners and I highly recommend that you compile and run the sample Java program yourself.

The following writing format will be used going forward and will provide you with:
– Description of the problem case and type of NoClassDefFoundError
– Sample Java program “simulating” the problem case
– ClassLoader chain view
– Recommendations and resolution strategies

NoClassDefFoundError problem case 1 – missing JAR file

The first problem case we will cover is related to a Java program packaging and / or classpath problem. A typical Java program can include one or many JAR files created at compile time. NoClassDefFoundError can often be observed when you forget to add JAR file(s) containing Java classes referenced by your Java or Java EE application.

This type of problem is normally not hard to resolve once you analyze the Java Exception and missing Java class name.

Sample Java program

The following simple Java program is split as per below:
– The main Java program NoClassDefFoundErrorSimulator
– The caller Java class CallerClassA
– The referencing Java class ReferencingClassA
– A util class for ClassLoader and logging related facilities JavaEETrainingUtil

This program is simple attempting to create a new instance and execute a method of the Java class CallerClassA which is referencing the class ReferencingClassA. It will demonstrate how a simple classpath problem can trigger NoClassDefFoundError. The program is also displaying detail on the current class loader chain at class loading time in order to help you keep track of this process. This will be especially useful for future and more complex problem cases when dealing with larger class loader chains.

package org.ph.javaee.training1;

import org.ph.javaee.training.util.JavaEETrainingUtil;

/**
 * NoClassDefFoundErrorTraining1
 * @author Pierre-Hugues Charbonneau
 *
 */
public class NoClassDefFoundErrorSimulator {
       
       
        /**
         * @param args
         */
        public static void main(String[] args) {
               System.out.println("java.lang.NoClassDefFoundError Simulator - Training 1");
               System.out.println("Author: Pierre-Hugues Charbonneau");
               System.out.println("http://javaeesupportpatterns.blogspot.com");
              
               // Print current Classloader context
               System.out.println("\nCurrent ClassLoader chain: "+JavaEETrainingUtil.getCurrentClassloaderDetail());
              
               // 1. Create a new instance of CallerClassA
               CallerClassA caller = new CallerClassA();
              
               // 2. Execute method of the caller
               caller.doSomething();
              
               System.out.println("done!");
        }
}
package org.ph.javaee.training1;

import org.ph.javaee.training.util.JavaEETrainingUtil;

/**
 * CallerClassA
 * @author Pierre-Hugues Charbonneau
 *
 */
public class CallerClassA {
       
        private final static String CLAZZ = CallerClassA.class.getName();
       
        static {
               System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail());
        }
       
        public CallerClassA() {
               System.out.println("Creating a new instance of "+CallerClassA.class.getName()+"...");
        }
       
        public void doSomething() {
              
               // Create a new instance of ReferencingClassA
               ReferencingClassA referencingClass = new ReferencingClassA();             
        }
}
package org.ph.javaee.training1;

import org.ph.javaee.training.util.JavaEETrainingUtil;

/**
 * ReferencingClassA
 * @author Pierre-Hugues Charbonneau
 *
 */
public class ReferencingClassA {

        private final static String CLAZZ = ReferencingClassA.class.getName();
       
        static {
               System.out.println("Classloading of "+CLAZZ+" in progress..."+JavaEETrainingUtil.getCurrentClassloaderDetail());
        }
       
        public ReferencingClassA() {
               System.out.println("Creating a new instance of "+ReferencingClassA.class.getName()+"...");
        }
       
        public void doSomething() {
               //nothing to do...
        }
}
package org.ph.javaee.training.util;

import java.util.Stack;
import java.lang.ClassLoader;

/**
 * JavaEETrainingUtil
 * @author Pierre-Hugues Charbonneau
 *
 */
public class JavaEETrainingUtil {
       
        /**
         * getCurrentClassloaderDetail
         * @return
         */
        public static String getCurrentClassloaderDetail() {
              
               StringBuffer classLoaderDetail = new StringBuffer();       
               Stack<ClassLoader> classLoaderStack = new Stack<ClassLoader>();
              
               ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
              
               classLoaderDetail.append("\n-----------------------------------------------------------------\n");
              
               // Build a Stack of the current ClassLoader chain
               while (currentClassLoader != null) {
              
                       classLoaderStack.push(currentClassLoader);
                      
                       currentClassLoader = currentClassLoader.getParent();
               }
              
               // Print ClassLoader parent chain
               while(classLoaderStack.size() > 0) {
                      
                       ClassLoader classLoader = classLoaderStack.pop();
                      
                       // Print current                     
                       classLoaderDetail.append(classLoader);
                      
                       if (classLoaderStack.size() > 0) {
                              classLoaderDetail.append("\n--- delegation ---\n");                               
                       } else {
                              classLoaderDetail.append(" **Current ClassLoader**");
                       }
               }
              
               classLoaderDetail.append("\n-----------------------------------------------------------------\n");
              
               return classLoaderDetail.toString();
        }
}

Problem reproduction

In order to replicate the problem, we will simply “voluntary” omit one of the JAR files from the classpath that contains the referencing Java class ReferencingClassA.

The Java program is packaged as per below:
– MainProgram.jar (contains NoClassDefFoundErrorSimulator.class and JavaEETrainingUtil.class )
-CallerClassA.jar (contains CallerClassA.class )
– ReferencingClassA.jar (contains ReferencingClassA.class )

Now, let’s run the program as is:

Recommendations and resolution strategies

## Baseline (normal execution)

..\bin>java -classpath CallerClassA.jar;ReferencingClassA.jar;MainProgram.jar org.ph.javaee.training1.NoClassDefFoundErrorSimulator

java.lang.NoClassDefFoundError Simulator - Training 1
Author: Pierre-Hugues Charbonneau
http://javaeesupportpatterns.blogspot.com

Current ClassLoader chain:
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader**
-----------------------------------------------------------------

Classloading of org.ph.javaee.training1.CallerClassA in progress...
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader**
-----------------------------------------------------------------

Creating a new instance of org.ph.javaee.training1.CallerClassA...
Classloading of org.ph.javaee.training1.ReferencingClassA in progress...
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader**
-----------------------------------------------------------------

Creating a new instance of org.ph.javaee.training1.ReferencingClassA...
done!

What happened? The removal of the ReferencingClassA.jar, containing ReferencingClassA, did prevent the current class loader to locate this referencing Java class at runtime leading to ClassNotFoundException and NoClassDefFoundError.

This is the typical Exception that you will get if you omit JAR file(s) from your Java start-up classpath or within an EAR / WAR for Java EE related applications.

ClassLoader view

Now let’s review the ClassLoader chain so you can properly understand this problem case. As you saw from the Java program output logging, the following Java ClassLoaders were found:

Classloading of org.ph.javaee.training1.CallerClassA in progress...
-----------------------------------------------------------------
sun.misc.Launcher$ExtClassLoader@17c1e333
--- delegation ---
sun.misc.Launcher$AppClassLoader@214c4ac9 **Current ClassLoader**
-----------------------------------------------------------------

** Please note that the Java bootstrap class loader is responsible to load the core JDK classes and is written in native code **

## sun.misc.Launcher$AppClassLoader

This is the system class loader responsible to load our application code found from the Java classpath specified at start-up.

##sun.misc.Launcher$ExtClassLoader

This is the extension class loader responsible to load code in the extensions directories (<java_home>/lib/ext, or any other directory specified by the java.ext.dirs system property).

As you can see from the Java program logging output, the extension class loader is the actual super parent of the system class loader. Our sample Java program was loaded at the system class loader level. Please note that this class loader chain is very simple for this problem case since we did not create child class loaders at this point. This will be covered in future articles.

Recommendations and resolution strategies

Now find below my recommendations and resolution strategies for NoClassDefFoundError problem case 1:

– Review the java.lang.NoClassDefFoundError error and identify the missing Java class 
-Verify and locate the missing Java class from your compile / build environment 
-Determine if the missing Java class is from your application code, third part API or even the Java EE container itself. Verify where the missing JAR file(s) is / are expected to be found
– Once found, verify your runtime environment Java classpath for any typo or missing JAR file(s)
– If the problem is triggered from a Java EE application, perform the same above steps but verify the packaging of your EAR / WAR file for missing JAR and other library file dependencies such as MANIFEST.

Please feel free to post any question or comment. The part 3 will be available shortly.

Reference: java.lang.NoClassDefFoundError: How to resolve – Part 2 from our JCG partner Pierre-Hugues Charbonneau at the Java EE Support Patterns & Java Tutorial blog.

Pierre Hugues Charbonneau

Pierre-Hugues Charbonneau (nickname P-H) is working for CGI Inc. Canada for the last 10 years as a senior IT consultant. His primary area of expertise is Java EE, middleware & JVM technologies. He is a specialist in production system troubleshooting, root cause analysis, middleware, JVM tuning, scalability and capacity improvement; including internal processes improvement for IT support teams. P-H is the principal author at Java EE Support Patterns.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gaurav
Gaurav
10 years ago

Hey, I am facing same problem that java.lang.NoClassDefFoundError:
Actually I have one jar file which I have added in my project in eclipse .
also, I have checked ,
1. Run Time class path
2. configured build path
3. also my manifest file is correst still I am getting an error java.lang.NoClassDefFoundError:.

Please help me its to complecated. and one thing that I worked with java but new user for IDE i.e. eclipse (juno)
So does anyone know or can help me out..??

Thanks .

Back to top button