How "Eclipse" resolves java.lang.NoClassDefFoundError errors

Source: Internet
Author: User

Objective

In the daily development of Java, we often encounter java.lang.NoClassDefFoundError such errors, it takes a lot of time to find the cause of the error, specifically which class is missing? The class is still there, why can't I find it? And it's easy to confuse both Java.lang.NoClassDefFoundError and java.lang.ClassNotfoundException, in fact the two errors are completely different. We often spend time trying other ways to solve this problem without really understanding the cause of the mistake. This article is to uncover some of Noclassdeffounderror's secrets by solving the experience sharing of noclassdeffounderror error handling. Noclassdeffounderror's errors are not unresolved or difficult to solve, but the form of this error can easily confuse other Java developers. Let's analyze why Noclassdeffounderror and how to solve this error.

Noclassdeffounderror Why the error occurred

The Noclassdeffounderror error occurs because the Java Virtual machine can find the appropriate class at compile time and cannot find the error caused by the appropriate class at run time. For example, when we want to invoke a method of a class or access a static member of the class at run time, we find that the class is not available, and the Java virtual machine throws a noclassdeffounderror error. Unlike classnotfoundexception, this error occurs only when the runtime needs to load the corresponding class unsuccessfully, not at compile time. It's easy for many Java developers to confuse the two errors here.

As a simple summary, noclassdeffounderror occurs when the corresponding class is available at compile time, while the runtime is in Java's classpath path, and the corresponding class is not usable as a result of the error. When a noclassdeffounderror error occurs, you can see the following error log:

1 Exception in thread "main" Java.lang.NoClassDefFoundError
View Code

The error message clearly indicates that the main thread could not find the specified class, which could be the main thread or other child threads. If the main thread has an error, the program crashes or stops, and if it is a child thread, the child thread stops and the other threads continue to run.

Noclassdeffounderror and ClassNotFoundException differences

We are often confused by the two errors of java.lang.ClassNotFoundException and Java.lang.NoClassDefFoundError, although they are all related to Java classpath, but they are completely different. Noclassdeffounderror occurs when the JVM is dynamically running, and the corresponding class is found in the classpath based on the class name you provide, but when it does not find the class, A java.lang.NoClassDefFoundError error occurs, and ClassNotFoundException is the error that occurs when the corresponding class is not found in classpath at compile time. ClassNotFoundException is easier to solve than noclassdeffounderror because we know that errors occur at compile time and are completely caused by environmental problems. And if you work in a Java EE environment and get noclassdeffounderror exceptions, and the corresponding error classes do exist, this means that the class may not be visible to the ClassLoader.

How to resolve Noclassdeffounderror errors

According to the previous article, it is obvious that the Noclassdeffounderror error is because at runtime the ClassLoader cannot find the class that needs to be loaded under classpath, so we need to load the corresponding class into classpath. Or check why the class is not available in classpath, this can happen for the following reasons:

    1. The corresponding class is not available in Java Classpath
    2. You may run your program with the jar command, but the class is not defined in the Classpath attribute in the jar file's manifest file
    3. The startup script of the possible program overrides the original CLASSPATH environment variable
    4. Because Noclassdeffounderror is a subclass of Java.lang.LinkageError, it may be caused by the unavailability of the native class library that the program relies on.
    5. Check the log file for errors such as Java.lang.ExceptionInInitializerError, Noclassdeffounderror may be caused by static initialization failure
    6. If you work in a Java EE environment, there are several different classloader that can also cause noclassdeffounderror

Let's look at some examples of how we should solve the noclassdeffounderror when it happens.

Noclassdeffounderror Solution Example
    • Java.lang.NoClassDefFoundError error occurs when a jar file is missing, or the jar file is not added to Classpath, or the file name of the jar is changed.
    • This is difficult to know when the class is not in Classpath, but if you print out System.getproperty ("Java.classpath") in the program, you can get the program to actually run Classpath
    • The runtime explicitly specifies the-classpath parameters that you think the program will function properly, and if the program works correctly after adding, the classpath of the original program is overwritten by others.
    • Noclassdeffounderror can also be caused by a static initialization module error for a class, and when your class performs some static initialization module operations, if the initialization module throws an exception, the other classes that depend on the class will throw noclassdeffounderror errors. If you look at the program log, you will find some Java.lang.ExceptionInInitializerError error logs, exceptionininitializererror the wrong Misunderstanding leads to Java.lang.NoClassDefFoundError:Could not initialize class, as in the following code example:
1 /**2 * Java program to demonstrate how failure of static initialization subsequently cause3 * Java.lang.NoClassDefFoundError in java.4  * @authorJavin Paul5  */6  Public classNoclassdeffounderrorduetostaticinitfailure {7 8      Public Static voidMain (String args[]) {9 Tenlist<user> users =NewArraylist<user> (2); One  A          for(inti=0; i<2; i++){ -             Try{ -Users.add (NewUser (string.valueof (i)));//Would throw Noclassdeffounderror the}Catch(Throwable t) { - t.printstacktrace (); -             } -         }          +     } - } +  A classuser{ at     Private StaticString user_id =getUserId (); -  -      PublicUser (String id) { -          This. USER_ID =ID; -     } -     Private StaticString getUserId () { in         Throw NewRuntimeException ("UserId not Found"); -     }      to } +  - Output the Java.lang.ExceptionInInitializerError *At testing. Noclassdeffounderrorduetostaticinitfailure.main (noclassdeffounderrorduetostaticinitfailure.java:23) $ caused by:java.lang.RuntimeException:UserId not foundPanax NotoginsengAt testing. User.getuserid (noclassdeffounderrorduetostaticinitfailure.java:41) -At testing. User.<clinit> (noclassdeffounderrorduetostaticinitfailure.java:35) the... 1 More +Java.lang.NoClassDefFoundError:Could not initializeclasstesting. User AAt testing. Noclassdeffounderrorduetostaticinitfailure.main (noclassdeffounderrorduetostaticinitfailure.java:23) the  +  -Read more:http://Javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz3dqtbvhdy
View Code

  • Because Noclassdeffounderror is a subclass of Linkageerror, and linkageerror errors occur when dependent on other classes, if your program relies on native class libraries and the required DLLs do not exist, Java.lang.NoClassDefFoundError may appear. This error can also throw exceptions such as Java.lang.UnsatisfiedLinkError:no DLL in Java.library.path Exception java. The solution is to put the dependent class libraries and DLLs together with your jar package.
  • If you use ant build scripts to generate jar files and manifest files, make sure that the ant script gets the correct Classpath value written to the MANIFEST.MF file
  • The permissions problem with the jar file may also cause noclassdeffounderror, if your program runs on a multi-user operating system like Linux, you need to assign the permissions of your application-related resource files, such as jar files, class library files, and configuration files, separately to the user group that the program belongs to. If you are using a jar package that is shared by multiple users in different programs, the permissions issue is very easy. For example, other user application permissions of the jar package your program does not have permission to access, can cause java.lang.NoClassDefFoundError errors.
  • Programs that are based on XML configuration can also cause noclassdeffounderror errors. For example, most Java frameworks like spring,struts use XML configuration to get the corresponding bean information, and if you enter the wrong name, the program may load other wrong classes and cause noclassdeffounderror exceptions. We are using the Spring MVC Framework or the Apache Struts framework, which often appears in the exception in thread "main" java.lang.NoClassDefFoundError when deploying a war file or ear file.
  • In an environment where there are multiple classloader of Java EE, it is easy to noclassdeffounderror errors. Since the Java EE does not specify a standard ClassLoader, the ClassLoader used depends on different components like Tomcat, weblogic,websphere loading the Java EE, or the Ejb-jar package. You can refer to this article about how the ClassLoader works with knowledge of the ClassLoader.

    In summary, the ClassLoader is based on three mechanisms: delegate, visibility, and uniqueness, which means that the request to load a class is given to the parent ClassLoader, and if the parent loader is not able to find or load the class, then load it. The principle of visibility is that the classloader of the subclass can see all the classes loaded by the parent ClassLoader, and the parent ClassLoader does not see the classes loaded by the child ClassLoader. The principle of uniqueness is to load only one class at a time, which is determined by the delegation mechanism to ensure that the subclass loader does not load the class loaded by the parent ClassLoader again. Now suppose that a user class exists in both the war file and the Ejb-jar file, and is loaded by the war ClassLoader, and the war ClassLoader is a classloader that loads Ejb-jar ClassLoader. When the code in Ejb-jar refers to this user class, the ClassLoader that loads Ejb-jar All classes cannot find this class because the class has been loaded by ClassLoader ClassLoader's sub-loader war.

    This results in a Noclassdeffounderror exception to the user class, and if the user class exists in two jar packages, classcastexception exception occurs if you use the Equals method to compare objects of two classes. Because classes loaded by two different classloader cannot be compared.

  • Sometimes exception in thread "main" java.lang.noclassdeffounderror:com/sun/tools/javac/main such errors, this error indicates your classpath, PATH or java_home is not properly configured or the JDK is not installed correctly. The solution to this problem is to reinstall your JDK.

  • Java can also cause noclassdeffounderror when performing linking operations. For example, in the previous script, if we delete the user's compiled file after compiling, and then run the program, you will get noclassdeffounderror directly, and the wrong message only prints out the name of the user class.
1 java.lang.noclassdeffounderror:testing/User2at     testing. Noclassdeffounderrorduetostaticinitfailure.main (noclassdeffounderrorduetostaticinitfailure.java:23)
View Code

Now we know how to deal with noclassdeffounderror anomalies and solve them.

How "Eclipse" resolves java.lang.NoClassDefFoundError errors

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.