Ошибка java lang noclassdeffounderror

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?

While it’s possible that this is due to a classpath mismatch between compile-time and run-time, it’s not necessarily true.

It is important to keep two or three different exceptions straight in our head in this case:

  1. java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

  2. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason — now we’re trying to use the class again (and thus need to load it, since it failed last time), but we’re not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

OldPeculier's user avatar

OldPeculier

10.8k12 gold badges48 silver badges74 bronze badges

answered Apr 22, 2011 at 15:28

Jared's user avatar

11

This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

answered Aug 29, 2008 at 15:01

Mocky's user avatar

MockyMocky

7,7055 gold badges27 silver badges23 bronze badges

8

Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared’s answer for detailed explanation.

NoClassDefFoundErrorDemo.java

public class NoClassDefFoundErrorDemo {
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleCalculator calculator1 = new SimpleCalculator();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleCalculator calculator2 = new SimpleCalculator();
    }

}

SimpleCalculator.java

public class SimpleCalculator {
    static int undefined = 1 / 0;
}

answered Feb 13, 2015 at 19:20

xli's user avatar

xlixli

2,3502 gold badges20 silver badges27 bronze badges

3

NoClassDefFoundError In Java

Definition:

  1. Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.

  2. If a class was present during compile time but not available in java classpath during runtime.

enter image description here

Examples:

  1. The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty(«java.classpath») and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
  2. A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar’s name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what’s wrong.

  3. Just try to run with explicitly -classpath option with the classpath you think will work and if it’s working then it’s a sure short sign that someone is overriding java classpath.

  4. Permission issue on JAR file can also cause NoClassDefFoundError in Java.
  5. Typo on XML Configuration can also cause NoClassDefFoundError in Java.
  6. when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.

Possible Solutions:

  1. The class is not available in Java Classpath.
  2. 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.
  3. Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
  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. Any start-up script is overriding Classpath environment variable.
  6. You might be running your program using jar command and class was not defined in manifest file’s ClassPath attribute.

Resources:

3 ways to solve NoClassDefFoundError

java.lang.NoClassDefFoundError Problem patterns

answered Aug 10, 2016 at 17:16

Aftab's user avatar

AftabAftab

2,84330 silver badges40 bronze badges

3

I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

set classpath=%classpath%;axis.jar

I was able to get it to pick up the proper version by using:

set classpath=axis.jar;%classpath%;

answered Aug 29, 2008 at 15:06

shsteimer's user avatar

shsteimershsteimer

28.2k29 gold badges78 silver badges95 bronze badges

2

One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:

  1. throw a RuntimeException in the static block of your class Example
  2. Intercept it (or if it just doesn’t matter like it is thrown in a test case)
  3. Try to create an instance of this class Example
static class Example {
    static {
        thisThrowsRuntimeException();
    }
}

static class OuterClazz {

    OuterClazz() {
        try {
            new Example();
        } catch (Throwable ignored) { //simulating catching RuntimeException from static block
            // DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
        }

        new Example(); //this throws NoClassDefFoundError
    }
}

NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.


This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.

In a way you’re «sharing» the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.

Charlie's user avatar

Charlie

8,3712 gold badges53 silver badges52 bronze badges

answered Dec 4, 2018 at 16:04

Bartek Lipinski's user avatar

Bartek LipinskiBartek Lipinski

30.2k10 gold badges93 silver badges131 bronze badges

1

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this:
enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
enter image description here

answered Sep 15, 2015 at 18:44

Ram Patra's user avatar

Ram PatraRam Patra

16k13 gold badges65 silver badges76 bronze badges

I was using Spring Framework with Maven and solved this error in my project.

There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.

Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.

@xli’s answer gave me insight into what may be wrong in my code.

Peter Mortensen's user avatar

answered Aug 10, 2015 at 8:16

Nikhil Sahu's user avatar

Nikhil SahuNikhil Sahu

2,3732 gold badges36 silver badges47 bronze badges

1

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;
            }
        });
    }
}

answered Sep 9, 2015 at 12:02

codeDr's user avatar

codeDrcodeDr

1,50517 silver badges19 bronze badges

1

The technique below helped me many times:

System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());

where the TheNoDefFoundClass is the class that might be «lost» due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.

answered Jul 27, 2016 at 13:44

Aram Paronikyan's user avatar

Java ClassNotFoundException vs NoClassDefFoundError

[ClassLoader]

Static vs Dynamic class loading

Static(Implicit) class loading — result of reference, instantiation, or inheritance.

MyClass myClass = new MyClass();

Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()

MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

Every class has a ClassLoader which uses loadClass(String name); that is why

explicit class loader uses implicit class loader

NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.

ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used — for example reflection.

answered Mar 26, 2021 at 11:25

yoAlex5's user avatar

yoAlex5yoAlex5

26.6k8 gold badges180 silver badges191 bronze badges

In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.

See Stack Overflow question How to increase the Java stack size?.

Peter Mortensen's user avatar

answered Nov 7, 2016 at 14:03

Aykut Kllic's user avatar

Aykut KllicAykut Kllic

8789 silver badges14 bronze badges

2

Two different checkout copies of the same project

In my case, the problem was Eclipse’s inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.

Closing the trunk copy of the project and running the test case again got rid of the problem.

answered Oct 25, 2017 at 6:58

manuelvigarcia's user avatar

manuelvigarciamanuelvigarcia

1,3961 gold badge18 silver badges31 bronze badges

I fixed my problem by disabling the preDexLibraries for all modules:

dexOptions {
        preDexLibraries false
        ...

answered Feb 5, 2018 at 2:34

Michael's user avatar

MichaelMichael

6466 silver badges16 bronze badges

0

I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program’s JVM option(It’s one megabyte by default since JDK5.0). It’s believed the program does not have enough stack to load class.

answered Nov 1, 2019 at 4:48

Alan Ackart's user avatar

In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn’t working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.

answered Feb 24, 2020 at 20:30

Ben Waters's user avatar

Ben WatersBen Waters

1471 silver badge8 bronze badges

Update [https://www.infoq.com/articles/single-file-execution-java11/]:

In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don’t have to run javac + java (of course,
leaving them confused why that is).

answered Aug 15, 2020 at 15:11

logbasex's user avatar

logbasexlogbasex

1,3921 gold badge13 silver badges18 bronze badges

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

answered Sep 27, 2018 at 20:30

ᴠɪɴᴄᴇɴᴛ's user avatar

ᴠɪɴᴄᴇɴᴛᴠɪɴᴄᴇɴᴛ

1,5732 gold badges22 silver badges28 bronze badges

5

I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.

Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.

Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..

answered Mar 18, 2021 at 12:47

priyanka_rao's user avatar

priyanka_raopriyanka_rao

4651 gold badge4 silver badges20 bronze badges

If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn’t add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.

answered Jun 19, 2017 at 13:48

ST7's user avatar

ST7ST7

2,1521 gold badge20 silver badges13 bronze badges

This error can be caused by unchecked Java version requirements.

In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.

sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu

Then doing a clean install as described below.


When using Maven as your build tool, it is sometimes helpful — and usually gratifying, to do a clean ‘install’ build with testing disabled.

mvn clean install -DskipTests

Now that everything has been built and installed, you can go ahead and run the tests.

mvn test

answered Apr 1, 2018 at 19:09

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.7k17 gold badges146 silver badges169 bronze badges

It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.

answered Aug 6, 2019 at 15:35

off99555's user avatar

off99555off99555

3,5793 gold badges32 silver badges46 bronze badges

Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).

answered Feb 29, 2020 at 17:07

bdskfsdk321dsad3's user avatar

I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

answered May 15, 2020 at 17:42

pixel's user avatar

pixelpixel

8,90416 gold badges72 silver badges135 bronze badges

I had this error but could not figure out the solution based on this thread but solved it myself.

For my problem I was compiling this code:

package valentines;

import java.math.BigInteger;
import java.util.ArrayList;

public class StudentSolver {
    public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
        //DOING WORK HERE
        
    }
    public static void main(String[] args){
        //TESTING SOLVE FUNCTION
    }
    
}

I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver

I was getting the NoClassDefError.

To fix this I simply removed: package valentines;

I’m not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn’t interpret it to my problem.

answered Sep 30, 2020 at 0:50

Thomas McSwain's user avatar

My solution to this was to «avail» the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac …, I was not able to run the resulting class file using java …, because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.

javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java

So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got

Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError: 
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider

And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.

answered Nov 21, 2022 at 14:15

douglas's user avatar

Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).

And the problem gone away.

answered Nov 29, 2017 at 12:51

Pekmezli Dürüm's user avatar

I had the same problem, and I was stock for many hours.

I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.

For example,

private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");

Peter Mortensen's user avatar

answered Jul 14, 2016 at 19:46

sudar's user avatar

sudarsudar

1,4262 gold badges14 silver badges26 bronze badges

I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.

My solution was: Restart Eclipse. Since then I haven’t seen this message again :-)

Peter Mortensen's user avatar

answered Oct 14, 2015 at 10:19

Eliran's user avatar

EliranEliran

591 silver badge8 bronze badges

1

Я потратил довольно много времени, чтобы выяснить как исправить ошибку java.lang.NoClassDefFoundError в Java.

В этой инструкции я покажу как исправить эти ошибки, раскрою некоторые секреты NoClassDefFoundError и поделюсь своим опытом в этой области.

NoClassDefFoundError – это самая распространенная ошибка в разработке Java. В любом случае, давайте посмотрим, почему это происходит и что нужно сделать для разрешения проблемы.
ошибка NoClassDefFoundError Java

NoClassDefFoundError в Java возникает, когда виртуальная машина Java не может найти определенный класс во время выполнения, который был доступен во время компиляции.

Например, если у нас есть вызов метода из класса или доступ к любому статическому члену класса, и этот класс недоступен во время выполнения, JVM сгенерирует NoClassDefFoundError.

Важно понимать, что это отличается от ClassNotFoundException, который появляется при попытке загрузить класс только во время выполнения, а имя было предоставлено во время выполнения, а не во время компиляции. Многие Java-разработчики смешивают эти две ошибки и запутываются.

NoClassDefFoundError возникнет, если класс присутствовал во время компиляции, но не был доступен в java classpath во время выполнения. Обычно появляется такая ошибка:

Exception in thread "main" java.lang.NoClassDefFoundError

Разница между java.lang.NoClassDefFoundError и ClassNotFoundException в Java

[ads-pc-3]
java.lang.ClassNotFoundException и java.lang.NoClassDefFoundError оба связаны с Java Classpath, и они полностью отличаются друг от друга.

ClassNotFoundException возникает, когда JVM пытается загрузить класс во время выполнения, т.е. вы даете имя класса во время выполнения, а затем JVM пытается загрузить его, и если этот класс не найден, он генерирует исключение java.lang.ClassNotFoundException.

Тогда как в случае NoClassDefFoundError проблемный класс присутствовал во время компиляции, и поэтому программа успешно скомпилирована, но не доступна во время выполнения по любой причине.

Приступим к решению ошибки java.lang.NoClassDefFoundError.

Нам нужно добавить NoClassDefFoundError в Classpath или проверить, почему он не доступен в Classpath. Там может быть несколько причин, таких как:

  1. Класс недоступен в Java Classpath.
  2. Возможно, вы запускаете вашу программу с помощью jar, а класс не определен в атрибуте ClassPath.
  3. Любой сценарий запуска переопределяет переменную среды Classpath.
    Поскольку NoClassDefFoundError является подклассом java.lang.LinkageError, он также может появиться, если библиотека может быть недоступна.
  4. Проверьте наличие java.lang.ExceptionInInitializerError в файле журнала. NoClassDefFoundError из-за сбоя инициализации встречается довольно часто.
  5. Если вы работаете в среде J2EE, то видимость Class среди нескольких Classloader также может вызвать java.lang.NoClassDefFoundError.

Примеры

  1. Простой пример NoClassDefFoundError – класс принадлежит отсутствующему файлу JAR, или JAR не был добавлен в путь к классам, или имя jar было изменено кем-то.
  2. Класс не находится в Classpath, нет способа узнать это, но вы можете просто посмотреть в System.getproperty (“java.classpath”), и он напечатает classpath оттуда, где можно получить представление о фактическом пути к классам во время выполнения.
  3. Просто попробуйте запустить явно -classpath с тем классом, который, по вашему мнению, будет работать, и если он работает, это верный признак того – что-то переопределяет java classpath.

NoClassDefFoundError в Java из-за исключения в блоке инициализатора

Это еще одна распространенная причина java.lang.NoClassDefFoundError, когда ваш класс выполняет некоторую инициализацию в статическом блоке и если статический блок генерирует исключение, класс, который ссылается на этот класс, получит NoclassDefFoundError.

Смотрите в журнале java.lang.ExceptionInInitializerError, потому что это может вызвать java.lang.NoClassDefFoundError: Could not initialize class.

Как и в следующем примере кода, во время загрузки и инициализации класса, пользовательский класс генерирует Exception из статического блока инициализатора, который вызывает ExceptionInInitializerError при первой загрузке пользовательского класса в ответ на новый вызов User ().
[ads-pc-3]

/**
 * Java program to demonstrate how failure of static initialization subsequently cause
 * java.lang.NoClassDefFoundError in Java.
 * @author Javin Paul
 */
public class NoClassDefFoundErrorDueToStaticInitFailure {

   public static void main(String args[]){
        
        List users = new ArrayList(2);
        
       for(int i=0; i<2; i++){
           try{
            users.add(new User(String.valueOf(i)));
           }catch(Throwable t){
                t.printStackTrace();
           }
       }         
   }
}

class User{
   private static String USER_ID = getUserId();
    
   public User(String id){
       this.USER_ID = id;
   }
   private static String getUserId() {
       throw new RuntimeException("UserId Not found");
   }     
}

Output
java.lang.ExceptionInInitializerError
at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)
Caused by: java.lang.RuntimeException: UserId Not found
    at testing.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:41)
    at testing.User.(NoClassDefFoundErrorDueToStaticInitFailure.java:35)
    ... 1 more
java.lang.NoClassDefFoundError: Could not initialize class testing.User
at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)
  1. Поскольку NoClassDefFoundError также является LinkageError, который возникает из-за зависимости от какого-либо другого класса, вы также можете получить java.lang.NoClassDefFoundError, если ваша программа зависит от собственной библиотеки, а соответствующая DLL отсутствует. Помните, что это может также вызвать java.lang.UnsatisfiedLinkError: no dll in java.library.path. Чтобы решить эту проблему, держите dll вместе с JAR.
  2. Если вы используете файл ANT, создайте JAR, стоит отметить отладку до этого уровня, чтобы убедиться, что скрипт компоновки ANT получает правильное значение classpath и добавляет его в файл manifest.mf.
  3. Проблема с правами доступа к файлу JAR. Если вы работаете с Java-программой в многопользовательской операционной системе, такой как Linux, вам следует использовать идентификатор пользователя приложения для всех ресурсов приложения, таких как файлы JAR, библиотеки и конфигурации. Если вы используете разделяемую библиотеку, которая используется несколькими приложениями, работающими под разными пользователями, вы можете столкнуться с проблемой прав доступа, например, файл JAR принадлежит другому пользователю и недоступен для вашего приложения.
  4. Опечатка в конфигурации XML также может вызвать NoClassDefFoundError в Java. Как и большинство Java-фреймворков, таких как Spring, Struts все они используют конфигурацию XML для определения bean-компонентов. В любом случае, если вы неправильно указали имя компонента, он может вызвать ошибку при загрузке другого класса. Это довольно часто встречается в среде Spring MVC и в Apache Struts, где вы получаете множество исключений при развертывании файла WAR или EAR.
  5. Когда ваш скомпилированный класс, который определен в пакете, не присутствует в том же пакете во время загрузки, как в случае с JApplet.
  6. Еще одна причина- это нескольких загрузчиков классов в средах J2EE. Поскольку J2EE не использует стандартную структуру загрузчика классов, а зависит от Tomcat, WebLogic, WebSphere и т.д., от того, как они загружают различные компоненты J2EE, такие как WAR-файл или EJB-JAR-файл. Кроме того, если класс присутствует в обоих файлах JAR и вы вызовете метод equals для сравнения этих двух объектов, это приведет к исключению ClassCastException, поскольку объект, загруженный двумя различными загрузчиками классов, не может быть равным.
  7. Очень редко может происходить Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/tools/javac/Main. Эта ошибка означает, что либо ваш Classpath, PATH или JAVA_HOME не настроен должным образом, либо JDK установка не правильная. Попробуйте переустановить JDK. Замечено, что проблема возникала после установки jdk1.6.0_33 и последующей переустановки JDK1.6.0_25.

While it’s possible that this is due to a classpath mismatch between compile-time and run-time, it’s not necessarily true.

It is important to keep two or three different exceptions straight in our head in this case:

  1. java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

  2. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason — now we’re trying to use the class again (and thus need to load it, since it failed last time), but we’re not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

OldPeculier's user avatar

OldPeculier

10.8k12 gold badges48 silver badges74 bronze badges

answered Apr 22, 2011 at 15:28

Jared's user avatar

11

This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

answered Aug 29, 2008 at 15:01

Mocky's user avatar

MockyMocky

7,7055 gold badges27 silver badges23 bronze badges

8

Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared’s answer for detailed explanation.

NoClassDefFoundErrorDemo.java

public class NoClassDefFoundErrorDemo {
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleCalculator calculator1 = new SimpleCalculator();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleCalculator calculator2 = new SimpleCalculator();
    }

}

SimpleCalculator.java

public class SimpleCalculator {
    static int undefined = 1 / 0;
}

answered Feb 13, 2015 at 19:20

xli's user avatar

xlixli

2,3502 gold badges20 silver badges27 bronze badges

3

NoClassDefFoundError In Java

Definition:

  1. Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.

  2. If a class was present during compile time but not available in java classpath during runtime.

enter image description here

Examples:

  1. The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty(«java.classpath») and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
  2. A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar’s name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what’s wrong.

  3. Just try to run with explicitly -classpath option with the classpath you think will work and if it’s working then it’s a sure short sign that someone is overriding java classpath.

  4. Permission issue on JAR file can also cause NoClassDefFoundError in Java.
  5. Typo on XML Configuration can also cause NoClassDefFoundError in Java.
  6. when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.

Possible Solutions:

  1. The class is not available in Java Classpath.
  2. 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.
  3. Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
  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. Any start-up script is overriding Classpath environment variable.
  6. You might be running your program using jar command and class was not defined in manifest file’s ClassPath attribute.

Resources:

3 ways to solve NoClassDefFoundError

java.lang.NoClassDefFoundError Problem patterns

answered Aug 10, 2016 at 17:16

Aftab's user avatar

AftabAftab

2,84330 silver badges40 bronze badges

3

I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

set classpath=%classpath%;axis.jar

I was able to get it to pick up the proper version by using:

set classpath=axis.jar;%classpath%;

answered Aug 29, 2008 at 15:06

shsteimer's user avatar

shsteimershsteimer

28.2k29 gold badges78 silver badges95 bronze badges

2

One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:

  1. throw a RuntimeException in the static block of your class Example
  2. Intercept it (or if it just doesn’t matter like it is thrown in a test case)
  3. Try to create an instance of this class Example
static class Example {
    static {
        thisThrowsRuntimeException();
    }
}

static class OuterClazz {

    OuterClazz() {
        try {
            new Example();
        } catch (Throwable ignored) { //simulating catching RuntimeException from static block
            // DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
        }

        new Example(); //this throws NoClassDefFoundError
    }
}

NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.


This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.

In a way you’re «sharing» the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.

Charlie's user avatar

Charlie

8,3712 gold badges53 silver badges52 bronze badges

answered Dec 4, 2018 at 16:04

Bartek Lipinski's user avatar

Bartek LipinskiBartek Lipinski

30.2k10 gold badges93 silver badges131 bronze badges

1

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this:
enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
enter image description here

answered Sep 15, 2015 at 18:44

Ram Patra's user avatar

Ram PatraRam Patra

16k13 gold badges65 silver badges76 bronze badges

I was using Spring Framework with Maven and solved this error in my project.

There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.

Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.

@xli’s answer gave me insight into what may be wrong in my code.

Peter Mortensen's user avatar

answered Aug 10, 2015 at 8:16

Nikhil Sahu's user avatar

Nikhil SahuNikhil Sahu

2,3732 gold badges36 silver badges47 bronze badges

1

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;
            }
        });
    }
}

answered Sep 9, 2015 at 12:02

codeDr's user avatar

codeDrcodeDr

1,50517 silver badges19 bronze badges

1

The technique below helped me many times:

System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());

where the TheNoDefFoundClass is the class that might be «lost» due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.

answered Jul 27, 2016 at 13:44

Aram Paronikyan's user avatar

Java ClassNotFoundException vs NoClassDefFoundError

[ClassLoader]

Static vs Dynamic class loading

Static(Implicit) class loading — result of reference, instantiation, or inheritance.

MyClass myClass = new MyClass();

Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()

MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

Every class has a ClassLoader which uses loadClass(String name); that is why

explicit class loader uses implicit class loader

NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.

ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used — for example reflection.

answered Mar 26, 2021 at 11:25

yoAlex5's user avatar

yoAlex5yoAlex5

26.6k8 gold badges180 silver badges191 bronze badges

In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.

See Stack Overflow question How to increase the Java stack size?.

Peter Mortensen's user avatar

answered Nov 7, 2016 at 14:03

Aykut Kllic's user avatar

Aykut KllicAykut Kllic

8789 silver badges14 bronze badges

2

Two different checkout copies of the same project

In my case, the problem was Eclipse’s inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.

Closing the trunk copy of the project and running the test case again got rid of the problem.

answered Oct 25, 2017 at 6:58

manuelvigarcia's user avatar

manuelvigarciamanuelvigarcia

1,3961 gold badge18 silver badges31 bronze badges

I fixed my problem by disabling the preDexLibraries for all modules:

dexOptions {
        preDexLibraries false
        ...

answered Feb 5, 2018 at 2:34

Michael's user avatar

MichaelMichael

6466 silver badges16 bronze badges

0

I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program’s JVM option(It’s one megabyte by default since JDK5.0). It’s believed the program does not have enough stack to load class.

answered Nov 1, 2019 at 4:48

Alan Ackart's user avatar

In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn’t working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.

answered Feb 24, 2020 at 20:30

Ben Waters's user avatar

Ben WatersBen Waters

1471 silver badge8 bronze badges

Update [https://www.infoq.com/articles/single-file-execution-java11/]:

In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don’t have to run javac + java (of course,
leaving them confused why that is).

answered Aug 15, 2020 at 15:11

logbasex's user avatar

logbasexlogbasex

1,3921 gold badge13 silver badges18 bronze badges

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

answered Sep 27, 2018 at 20:30

ᴠɪɴᴄᴇɴᴛ's user avatar

ᴠɪɴᴄᴇɴᴛᴠɪɴᴄᴇɴᴛ

1,5732 gold badges22 silver badges28 bronze badges

5

I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.

Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.

Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..

answered Mar 18, 2021 at 12:47

priyanka_rao's user avatar

priyanka_raopriyanka_rao

4651 gold badge4 silver badges20 bronze badges

If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn’t add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.

answered Jun 19, 2017 at 13:48

ST7's user avatar

ST7ST7

2,1521 gold badge20 silver badges13 bronze badges

This error can be caused by unchecked Java version requirements.

In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.

sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu

Then doing a clean install as described below.


When using Maven as your build tool, it is sometimes helpful — and usually gratifying, to do a clean ‘install’ build with testing disabled.

mvn clean install -DskipTests

Now that everything has been built and installed, you can go ahead and run the tests.

mvn test

answered Apr 1, 2018 at 19:09

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.7k17 gold badges146 silver badges169 bronze badges

It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.

answered Aug 6, 2019 at 15:35

off99555's user avatar

off99555off99555

3,5793 gold badges32 silver badges46 bronze badges

Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).

answered Feb 29, 2020 at 17:07

bdskfsdk321dsad3's user avatar

I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

answered May 15, 2020 at 17:42

pixel's user avatar

pixelpixel

8,90416 gold badges72 silver badges135 bronze badges

I had this error but could not figure out the solution based on this thread but solved it myself.

For my problem I was compiling this code:

package valentines;

import java.math.BigInteger;
import java.util.ArrayList;

public class StudentSolver {
    public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
        //DOING WORK HERE
        
    }
    public static void main(String[] args){
        //TESTING SOLVE FUNCTION
    }
    
}

I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver

I was getting the NoClassDefError.

To fix this I simply removed: package valentines;

I’m not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn’t interpret it to my problem.

answered Sep 30, 2020 at 0:50

Thomas McSwain's user avatar

My solution to this was to «avail» the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac …, I was not able to run the resulting class file using java …, because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.

javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java

So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got

Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError: 
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider

And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.

answered Nov 21, 2022 at 14:15

douglas's user avatar

Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).

And the problem gone away.

answered Nov 29, 2017 at 12:51

Pekmezli Dürüm's user avatar

I had the same problem, and I was stock for many hours.

I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.

For example,

private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");

Peter Mortensen's user avatar

answered Jul 14, 2016 at 19:46

sudar's user avatar

sudarsudar

1,4262 gold badges14 silver badges26 bronze badges

I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.

My solution was: Restart Eclipse. Since then I haven’t seen this message again :-)

Peter Mortensen's user avatar

answered Oct 14, 2015 at 10:19

Eliran's user avatar

EliranEliran

591 silver badge8 bronze badges

1

While it’s possible that this is due to a classpath mismatch between compile-time and run-time, it’s not necessarily true.

It is important to keep two or three different exceptions straight in our head in this case:

  1. java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

  2. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason — now we’re trying to use the class again (and thus need to load it, since it failed last time), but we’re not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

OldPeculier's user avatar

OldPeculier

10.8k12 gold badges48 silver badges74 bronze badges

answered Apr 22, 2011 at 15:28

Jared's user avatar

11

This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

answered Aug 29, 2008 at 15:01

Mocky's user avatar

MockyMocky

7,7055 gold badges27 silver badges23 bronze badges

8

Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared’s answer for detailed explanation.

NoClassDefFoundErrorDemo.java

public class NoClassDefFoundErrorDemo {
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleCalculator calculator1 = new SimpleCalculator();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleCalculator calculator2 = new SimpleCalculator();
    }

}

SimpleCalculator.java

public class SimpleCalculator {
    static int undefined = 1 / 0;
}

answered Feb 13, 2015 at 19:20

xli's user avatar

xlixli

2,3502 gold badges20 silver badges27 bronze badges

3

NoClassDefFoundError In Java

Definition:

  1. Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.

  2. If a class was present during compile time but not available in java classpath during runtime.

enter image description here

Examples:

  1. The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty(«java.classpath») and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
  2. A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar’s name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what’s wrong.

  3. Just try to run with explicitly -classpath option with the classpath you think will work and if it’s working then it’s a sure short sign that someone is overriding java classpath.

  4. Permission issue on JAR file can also cause NoClassDefFoundError in Java.
  5. Typo on XML Configuration can also cause NoClassDefFoundError in Java.
  6. when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.

Possible Solutions:

  1. The class is not available in Java Classpath.
  2. 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.
  3. Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
  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. Any start-up script is overriding Classpath environment variable.
  6. You might be running your program using jar command and class was not defined in manifest file’s ClassPath attribute.

Resources:

3 ways to solve NoClassDefFoundError

java.lang.NoClassDefFoundError Problem patterns

answered Aug 10, 2016 at 17:16

Aftab's user avatar

AftabAftab

2,84330 silver badges40 bronze badges

3

I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.

set classpath=%classpath%;axis.jar

I was able to get it to pick up the proper version by using:

set classpath=axis.jar;%classpath%;

answered Aug 29, 2008 at 15:06

shsteimer's user avatar

shsteimershsteimer

28.2k29 gold badges78 silver badges95 bronze badges

2

One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:

  1. throw a RuntimeException in the static block of your class Example
  2. Intercept it (or if it just doesn’t matter like it is thrown in a test case)
  3. Try to create an instance of this class Example
static class Example {
    static {
        thisThrowsRuntimeException();
    }
}

static class OuterClazz {

    OuterClazz() {
        try {
            new Example();
        } catch (Throwable ignored) { //simulating catching RuntimeException from static block
            // DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
        }

        new Example(); //this throws NoClassDefFoundError
    }
}

NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.


This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.

In a way you’re «sharing» the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.

Charlie's user avatar

Charlie

8,3712 gold badges53 silver badges52 bronze badges

answered Dec 4, 2018 at 16:04

Bartek Lipinski's user avatar

Bartek LipinskiBartek Lipinski

30.2k10 gold badges93 silver badges131 bronze badges

1

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this:
enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
enter image description here

answered Sep 15, 2015 at 18:44

Ram Patra's user avatar

Ram PatraRam Patra

16k13 gold badges65 silver badges76 bronze badges

I was using Spring Framework with Maven and solved this error in my project.

There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.

Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.

@xli’s answer gave me insight into what may be wrong in my code.

Peter Mortensen's user avatar

answered Aug 10, 2015 at 8:16

Nikhil Sahu's user avatar

Nikhil SahuNikhil Sahu

2,3732 gold badges36 silver badges47 bronze badges

1

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;
            }
        });
    }
}

answered Sep 9, 2015 at 12:02

codeDr's user avatar

codeDrcodeDr

1,50517 silver badges19 bronze badges

1

The technique below helped me many times:

System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());

where the TheNoDefFoundClass is the class that might be «lost» due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.

answered Jul 27, 2016 at 13:44

Aram Paronikyan's user avatar

Java ClassNotFoundException vs NoClassDefFoundError

[ClassLoader]

Static vs Dynamic class loading

Static(Implicit) class loading — result of reference, instantiation, or inheritance.

MyClass myClass = new MyClass();

Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()

MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

Every class has a ClassLoader which uses loadClass(String name); that is why

explicit class loader uses implicit class loader

NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.

ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used — for example reflection.

answered Mar 26, 2021 at 11:25

yoAlex5's user avatar

yoAlex5yoAlex5

26.6k8 gold badges180 silver badges191 bronze badges

In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.

See Stack Overflow question How to increase the Java stack size?.

Peter Mortensen's user avatar

answered Nov 7, 2016 at 14:03

Aykut Kllic's user avatar

Aykut KllicAykut Kllic

8789 silver badges14 bronze badges

2

Two different checkout copies of the same project

In my case, the problem was Eclipse’s inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.

Closing the trunk copy of the project and running the test case again got rid of the problem.

answered Oct 25, 2017 at 6:58

manuelvigarcia's user avatar

manuelvigarciamanuelvigarcia

1,3961 gold badge18 silver badges31 bronze badges

I fixed my problem by disabling the preDexLibraries for all modules:

dexOptions {
        preDexLibraries false
        ...

answered Feb 5, 2018 at 2:34

Michael's user avatar

MichaelMichael

6466 silver badges16 bronze badges

0

I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program’s JVM option(It’s one megabyte by default since JDK5.0). It’s believed the program does not have enough stack to load class.

answered Nov 1, 2019 at 4:48

Alan Ackart's user avatar

In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn’t working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.

answered Feb 24, 2020 at 20:30

Ben Waters's user avatar

Ben WatersBen Waters

1471 silver badge8 bronze badges

Update [https://www.infoq.com/articles/single-file-execution-java11/]:

In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don’t have to run javac + java (of course,
leaving them confused why that is).

answered Aug 15, 2020 at 15:11

logbasex's user avatar

logbasexlogbasex

1,3921 gold badge13 silver badges18 bronze badges

NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:

try {
    // Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
    Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}

answered Sep 27, 2018 at 20:30

ᴠɪɴᴄᴇɴᴛ's user avatar

ᴠɪɴᴄᴇɴᴛᴠɪɴᴄᴇɴᴛ

1,5732 gold badges22 silver badges28 bronze badges

5

I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.

Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.

Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..

answered Mar 18, 2021 at 12:47

priyanka_rao's user avatar

priyanka_raopriyanka_rao

4651 gold badge4 silver badges20 bronze badges

If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn’t add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.

answered Jun 19, 2017 at 13:48

ST7's user avatar

ST7ST7

2,1521 gold badge20 silver badges13 bronze badges

This error can be caused by unchecked Java version requirements.

In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.

sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu

Then doing a clean install as described below.


When using Maven as your build tool, it is sometimes helpful — and usually gratifying, to do a clean ‘install’ build with testing disabled.

mvn clean install -DskipTests

Now that everything has been built and installed, you can go ahead and run the tests.

mvn test

answered Apr 1, 2018 at 19:09

Brent Bradburn's user avatar

Brent BradburnBrent Bradburn

49.7k17 gold badges146 silver badges169 bronze badges

It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.

answered Aug 6, 2019 at 15:35

off99555's user avatar

off99555off99555

3,5793 gold badges32 silver badges46 bronze badges

Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).

answered Feb 29, 2020 at 17:07

bdskfsdk321dsad3's user avatar

I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.

answered May 15, 2020 at 17:42

pixel's user avatar

pixelpixel

8,90416 gold badges72 silver badges135 bronze badges

I had this error but could not figure out the solution based on this thread but solved it myself.

For my problem I was compiling this code:

package valentines;

import java.math.BigInteger;
import java.util.ArrayList;

public class StudentSolver {
    public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
        //DOING WORK HERE
        
    }
    public static void main(String[] args){
        //TESTING SOLVE FUNCTION
    }
    
}

I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver

I was getting the NoClassDefError.

To fix this I simply removed: package valentines;

I’m not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn’t interpret it to my problem.

answered Sep 30, 2020 at 0:50

Thomas McSwain's user avatar

My solution to this was to «avail» the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac …, I was not able to run the resulting class file using java …, because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.

javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java

So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got

Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError: 
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider

And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.

answered Nov 21, 2022 at 14:15

douglas's user avatar

Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).

And the problem gone away.

answered Nov 29, 2017 at 12:51

Pekmezli Dürüm's user avatar

I had the same problem, and I was stock for many hours.

I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.

For example,

private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");

Peter Mortensen's user avatar

answered Jul 14, 2016 at 19:46

sudar's user avatar

sudarsudar

1,4262 gold badges14 silver badges26 bronze badges

I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.

My solution was: Restart Eclipse. Since then I haven’t seen this message again :-)

Peter Mortensen's user avatar

answered Oct 14, 2015 at 10:19

Eliran's user avatar

EliranEliran

591 silver badge8 bronze badges

1

Перевод: Саянкин А.А.

Содержание

  • 1 Введение
  • 2 В чём причина NoClassDefFoundError в Java?
  • 3 Разница между java.lang.NoClassDefFoundError и ClassNotFoundException в Java
  • 4 NoClassDefFoundError в Java. Примеры и сценарии
  • 5 Загрузчик классов в Java
  • 6 NoClassDefFoundError в Java из-за исключения в статическом инициализирующем блоке
  • 7 Перечень использованных ссылок

Предисловие переводчика


Данная статья представляет перевод оригинальных публикаций следующих авторов:

  • Джэйвин Пол (Javin Paul) Difference between ClassNotFoundException vs NoClassDefFoundError in Java, 3 ways to solve java.lang.NoClassDefFoundError in Java J2EE;
  • Пьер Хьюго Шарбоне (Pierre Hugues Charbonneau) java.lang.NoClassDefFoundError: How to resolve – Part 1;
  • coobird What is the difference between NoClassDefFoundError and ClassNotFoundException?

Переводчик выражает благодарность Виктору Жуковскому за ценные правки и обсуждение рукописи.

Введение

Известно насколько неприятно видеть исключение java.lang.NoClassDefFoundError в потоке «main«. Многие разработчики проводят много времени прежде всего пытаясь понять, что пошло не так, какого класса не хватает и в чём суть проблемы. Во-первых, они путают между собой ClassNotfoundException и NoClassDefFoundError, хотя на самом деле это два совершенно разных исключения. Во-вторых, они используют метод «научного тыка» для решения проблемы NoClassDefFoundError вместо ясного понимания почему ошибка случилась и как её исправить. В этой статье по Java мы откроем некоторые секреты исправления ошибки NoClassDefFoundError в Java и поделимся своим опытом решения подобной проблемы.

Ошибка NoClassDefFoundError не является чем-то, что не может быть устранено или чем-то, что очень трудно устраняемо — нет, NoClassDefFoundError всего лишь проявление другой, более глубинной ошибки, что сбивает с толку большинство Java разработчиков. NoClassDefFoundError наиболее распространённая ошибка в Java разработке наряду с java.lang.OutOfMemoroyError: Java heap space и java.lang.OutOfMemoryError: PermGen space. Давайте посмотрим почему в Java происходит NoClassDefFoundError и что делать, чтобы её исправить.

В чём причина NoClassDefFoundError в Java?

NoClassDefFoundError в Java происходит тогда, когда виртуальная машина Java во время исполнения кода не может найти определённый класс, который был доступен во время компиляции. Например, если мы вызываем метод из класса или обращаемся к статическому члену класса и этот класс не доступен во время выполнения, то виртуальная машина Java выбрасывает NoClassDefFoundError. Важно понимать, что эта ошибка отличается от исключения ClassNotFoundException, которое происходит при попытке загрузки класса во время выполнения, причём важно, что имя этого класса было определено только во время выполнения, но не во время компиляции кода. Многие Java разработчики путают эти две ошибки и приходят в тупик при попытке разрешить вопрос.

Коротко говоря, NoClassDefFoundError происходит, если класс присутствовал во время компиляции, но не доступен в classpath во время исполнения. Обычно в этом случае вы увидите следующую строку в журнале ошибок:

Exception in thread «main» java.lang.NoClassDefFoundError

Фраза Exception in thread «main» означает, что именно поток «main» не может найти определённый класс. Вместо «main» может быть любой поток. Разница между тем, когда эта ошибка возникает в потоке «main» и в другом потоке в состоит том, что при возникновении в потоке «main» программа останавливается, а при возникновении в ином потоке, напротив, продолжает выполнение после ошибки.

Разница между java.lang.NoClassDefFoundError и ClassNotFoundException в Java

Прежде чем рассмотреть разницу между ClassNotFoundException и NoClassDefFoundError давайте рассмотрим, что между ними общего и что приводит к путанице между этими двумя ошибками:

  • Обе ошибки связаны с недоступностью класса во время выполнения;
  • Обе ошибки связаны с Java Classpath .

Теперь о различиях.

  • ClassNotFoundException возникает в Java, если мы пытаемся загрузить класс во время выполнения используя методы Class.forName(), ClassLoader.loadClass() или ClassLoader.findSystemClass() , причём необходимый класс не доступен для Java. Зачастую причина тому — неправильный Classpath. В большинстве своём нам кажется, что мы используем корректный Classpath, но оказывается, что приложение использует совсем другой Classpath — не тот, который мы ожидали. Например, Classpath , заданный в манифесте jar файла, перезаписывает Classpath в переменной окружения CLASSPATH или опции -cp , заданной при запуске jar файла. В отличие от ClassNotFoundException в случае с NoClassDefFoundError проблемный класс присутствовал во время компиляции, и, поэтому, программа успешно прошла компиляцию, но по некоторой причине класс отсутствует во время исполнения. На мой взгляд решить NoClassDefFoundError легче чем ClassNotFoundException, поскольку вы точно знаете, что класс присутствовал во время сборки, но, в общем случае, это сильно зависит от среды разработки. Если вы работаете с J2EE окружением, вы можете получить NoClassDefFoundError даже если класс присутствует, поскольку он может быть невидимым для соответствующего загрузчика классов.
  • ClassNotFoundException представляет собой проверяемое исключение, унаследованное непосредственно от класса java.lang.Exception, требующее явной обработки, в то время как NoClassDefFoundError это java.lang.Error, унаследованный от java.lang.LinkageError.
  • ClassNotFoundException возникает в результате явной загрузки класса методами Class.forName(), ClassLoader.loadClass() или ClassLoader.findSystemClass(), в то время как NoClassDefFoundError — результат неявной загрузки класса, происходящей при попытке вызова метода из другого класса или доступа к его свойству.

NoClassDefFoundError в Java. Примеры и сценарии

Итак, очевидная причина NoClassDefFoundError состоит в том, что определённый класс не доступен в Classpath, так что нам нужно добавить его в Classpath или понять почему его нет в Classpath, хотя мы ожидаем его там найти. Для этого могут быть несколько причин:

  1. Класс не задан непосредственно в самой переменной Classpath.
    • Распечатайте значение System.getproperty(«java.classpath») в Java программе.
    • Проверьте, не перезаписывает ли значение переменной окружения Classpath скрипт, запускающий приложение. Запустите программу с явной опцией -classpath, где укажите тот classpath, который по вашему мнению сработает, и если в этом случае программа заработает, то это хороший знак, что кто-то перезатирает ваш classpath.
  2. Класс отсутствует по местоположению, указанному в переменной Classpath.
    • Проверьте, не удалил ли кто-то ваш jar-файл, или быть может переименовал его.
  3. Загрузчик классов не имеет прав на чтение файла, указанного в переменной Classpath, на уровне операционной системы.
    • Используйте один и тот же id пользователя для всех ресурсов вашего приложения: JAR файлов, библиотек и файлов конфигурации.
  4. Класс не определён в атрибуте ClassPath файла манифеста, при запуске программы с помощью команды jar.
    • Если вы используете файл сборки ANT для создания JAR архива и файла манифеста, то проверьте получает ли скрипт сборки ANT правильное значение classpath и добавляет ли его в файл manifest.mf.
  5. Виртуальная машина Java не нашла одну из зависимостей, например, нативную библиотеку. Эта ошибка выбрасывается поскольку NoClassDefFoundError является наследником java.lang.LinkageError.
    • Храните ваши dll совместно с jar-файлами.
  6. Виртуальная машина Java не смогла завершить статическую инициализацию класса.
    • Проверьте наличие ошибки java.lang.ExceptionInInitializerError в вашем журнале ошибок.
  7. Родительский загрузчик классов не видит класс, поскольку тот был уже загружен дочерним загрузчиком. Если вы работаете со средой J2EE, то неверная настройка видимости класса среди загрузчиков классов может также привести к java.lang.NoClassDefFoundError.
  8. Опечатка в XML конфигурации также может привести к NoClassDefFoundError в Java. Большинство программных платформ вроде Spring и Struts используют XML конфигурации для определения бинов. Случайно перепутав имя бина, вы можете получить java.lang.NoClassDefFoundError при загрузке другого класса, который зависит от бина. Это случается довольно часто в программных платформах Spring MVC и Apache Struts, где вы получаете тонны ошибок Exception in thread «main» java.lang.NoClassDefFoundError во время установки WAR или EAR файла.
  9. Переменные окружения или JDK установлены неверно.
    • Проверьте переменные PATH и JAVA_HOME.
    • Поставьте JDK другой версии.

Загрузчик классов в Java

Вкратце напомним, что загрузчик классов использует три основных принципа в своей работе: делегирование, видимость и уникальность.

  • Делегирование означает, что каждый запрос на загрузку класса делегируется родительскому загрузчику классов.
  • Видимость означает возможность найти классы загруженные загрузчиком классов: все дочерние загрузчики классов могут видеть классы, загруженные родительским загрузчиком, но родительский загрузчик не может видеть класс, загруженный дочерним.
  • Уникальность гарантирует, что класс, загруженный родительским загрузчиком, не загружается повторно дочерним загрузчиком.

Каждый экземпляр загрузчика классов имеет связанный с ним родительский загрузчик классов. Предположим, загрузчик классов вашего приложения должен загрузить класс A. Первым делом загрузчик классов вашего приложения попытается делегировать поиск класса A своему родительскому загрузчику, прежде чем сам попытается его загрузить. Вы можете пройтись по длинной цепочке родительских загрузчиков пока не дойдёте до стартового загрузчика виртуальной машины Java.

Так в чём же тут проблема? Если класс A найден и загружен каким-нибудь родительским загрузчиком, это значит, что дочерний загрузчик загружать его уже не будет, а вы, возможно, именно этого и ждёте, что и приводит к NoClassDefFoundError.

Для лучшего понимания изобразим весь процесс загрузки в контексте платформы Java EE.

Схема делегирования загрузки в контексте платформы Java EE

Как вы можете видеть при попытке загрузки класса дочерний загрузчик (Web App #1) делегирует загрузку родительскому загрузчику (Java EE App #1), который в свою очередь делегирует её системному стартовому загрузчику JVM. Если системный стартовый загрузчик не может загрузить класс, он возвращает управление родительскому загрузчику и так далее по цепочке пока класс не будет загружен каким-либо загрузчиком.

Рассмотрим простой пример, приводящий к NoClassDefFoundError из-за разной видимости классов между дочерним и родительским загрузчиками. Сделаем свой загрузчик MyClassLoader, наследник от java.lang.ClassLoader такой, чтобы он загружал классы с расширением .test вместо .class, находящиеся в пакете net.javacogito. Отметим, что стандартный загрузчик по умолчанию загружает данные только из файлов с расширением .class, так что загрузить Bar.test он не сможет. Схема дальнейшей работы такая:

  1. JVM загружает класс Bar из файла Bar.test.
  2. Класс Bar печатает свой загрузчик классов. Это MyClassLoader.
  3. JVM загружает класс Foo из файла Foo.class.
  4. Класс Foo печатает свой загрузчик классов. Это sun.misc.Launcher.AppClassLoader.
  5. Класс Foo вызывает статический метод printClassLoader() у класса Bar.

В этот момент JVM выдаёт NoClassDefFoundError, не смотря на то, что Bar был загружен ранее, поскольку родительский загрузчик AppClassLoader не видит классы, загруженные дочерним загрузчиком MyClassLoader.

Ниже на рисунке изображена схема делегирования загрузки, приводящая к NoClassDefFoundError.

Схема делегирования загрузки

Исходный код. Класс Bar.

package net.javacogito;
public class Bar {
    public static void printClassLoader() {
        System.out.println("Bar ClassLoader: " + Bar.class.getClassLoader());
    }
}

Класс Foo.

package net.javacogito;
public class Foo {
    public static  void printBarClassLoader(){
        Bar.printClassLoader();
    }
    public static void printClassLoader() {
        System.out.println("Foo ClassLoader: " + Foo.class.getClassLoader());
    }
}

Класс MyClassLoader.

package net.javacogito;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class MyClassLoader extends ClassLoader{
    public MyClassLoader(ClassLoader parent) {
        super(parent);
    }
    @Override
    public Class loadClass(String name) throws ClassNotFoundException {
        System.out.println("Loading Class '" + name + "'");
        if (name.startsWith("net.javacogito")) {
            System.out.println("Loading Class using MyClassLoader");
            return getClass(name);
        }
        return super.loadClass(name);
    }
    private Class getClass(String name) throws ClassNotFoundException {
        String file = name.replace('.', File.separatorChar) + ".test";
        byte[] b = null;
        try {
            b = loadClassFileData(file);
            Class c = defineClass(name, b, 0, b.length);
            resolveClass(c);
            return c;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    private byte[] loadClassFileData(String name) throws IOException {
        InputStream stream = getClass().getClassLoader().getResourceAsStream(name);
        int size = stream.available();
        byte buff[] = new byte[size];
        DataInputStream in = new DataInputStream(stream);
        in.readFully(buff);
        in.close();
        return buff;
    }
}

Класс Runner.

package net.javacogito;
import java.lang.reflect.Method;
public class Runner {
    public static void main(String[] args) throws Exception{
        MyClassLoader myClassLoader = new MyClassLoader(Runner.class.getClassLoader());
        Class clazz = myClassLoader.loadClass("net.javacogito.Bar");
        Method printClassLoader = clazz.getMethod("printClassLoader");
        printClassLoader.invoke(null, new Object[0]);
        Foo.printClassLoader();
        Foo.printBarClassLoader();
    }
}

Порядок запуска.

cd src/main/java
javac net/javacogito/Runner.java 
mv net/javacogito/Bar.class net/javacogito/Bar.test
java net.javacogito.Runner

Результат запуска.

Loading Class 'net.javacogito.Bar'
Loading Class using MyClassLoader
Loading Class 'java.lang.Object'
Loading Class 'java.lang.System'
Loading Class 'java.lang.StringBuilder'
Loading Class 'java.lang.Class'
Loading Class 'java.io.PrintStream'
Bar ClassLoader: net.javacogito.MyClassLoader@527c6768
Foo ClassLoader: sun.misc.Launcher$AppClassLoader@3326b249
Exception in thread "main" java.lang.NoClassDefFoundError: net/javacogito/Bar
        at net.javacogito.Foo.printBarClassLoader(Foo.java:5)
        at net.javacogito.Runner.main(Runner.java:16)
Caused by: java.lang.ClassNotFoundException: net.javacogito.Bar
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        ... 2 more

Из результатов запуска видно, что MyClassLoader загрузил класс Bar, а AppClassLoader (наследник абстрактного класса java.lang.ClassLoader) загрузил класс Foo. Класс Bar присутствует в файловой системе и JVM его загрузила, но родительский загрузчик ClassLoader не видит его, что и приводит к NoClassDefFoundError.

NoClassDefFoundError в Java из-за исключения в статическом инициализирующем блоке

Исключения в статическом инициализирующем блоке — другая частая причина java.lang.NoClassDefFoundError. Ваш класс выполняет некоторую статическую инициализацию в статическом блоке. Например, многие синглетоны инициализируют себя в статическом блоке, чтобы получить преимущества потоко-безопасности, предоставляемые виртуальной машиной Java во время процесса инициализации класса. В этом случае, если статический блок выбросит исключение, то класс, ссылающийся на этот синглетон, выбросит NoclassDefFoundError в Java. При просмотре вашего журнала ошибок вы должны внимательно следить, не возникла ли ошибка java.lang.ExceptionInInitializerError, поскольку она может привести к java.lang.NoClassDefFoundError: Could not initialize class в другом месте. Как и в примере кода ниже, во время загрузки и инициализации класс User выбрасывает исключение из статического инициализирующего блока, что приводит к ExceptionInInitializerError во время первой загрузки класса User при вызове new User(). Дальше все остальные вызовы new User() завершаются java.lang.NoClassDefFoundError. Ситуация становится намного хуже, если исходную ошибку ExceptionInInitializerError, являющуюся первопричиной, скрывает последующий код.

/**
* Java program to demonstrate how failure of static initialization subsequently cause
* java.lang.NoClassDefFoundError in Java.
* @author Javin Paul
*/
public class NoClassDefFoundErrorDueToStaticInitFailure {
    public static void main(String args[]){
        List<User> users = new ArrayList<User>(2);
        for(int i=0; i<2; i++){
        try{
            users.add(new User(String.valueOf(i))); //will throwNoClassDefFoundError
        }catch(Throwable t){
            t.printStackTrace();
            }
        }
    }
}

class User{
private static String USER_ID = getUserId();
public User(String id){
    this.USER_ID = id;
}
private static String getUserId() {
    throw new RuntimeException("UserId Not found");
    }
}

Результат запуска.

java.lang.ExceptionInInitializerError
at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDef
FoundErrorDueToStaticInitFailure.java:23)
Caused by: java.lang.RuntimeException: UserId Not found at
testing.User.getUserId(NoClassDefFoundErrorDueToStaticInitFailure.java:41)
at testing.User.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:35)
... 1 more
java.lang.NoClassDefFoundError: Could not initialize class
testing.User
at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDef
FoundErrorDueToStaticInitFailure.java:23)

Перечень использованных ссылок

  1. http://javarevisited.blogspot.com/2011/07/classnotfoundexception-vs.html
  2. http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html
  3. http://stackoverflow.com/questions/1457863/what-is-the-difference-between-noclassdeffounderror-and-classnotfoundexception
  4. http://www.javacodegeeks.com/2012/06/javalangnoclassdeffounderror-how-to.html

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка java lang illegalargumentexception как исправить
  • Ошибка java lang classcastexception
  • Ошибка java io ioexception stalcraft
  • Ошибка java faceit
  • Ошибка java error could not find java dll

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии