The correct solution to the java.lang.NoClassDefFoundError exception has been resolved, and the pro-test is effective! ! !

The correct solution to the java.lang.NoClassDefFoundError exception has been resolved, and the pro-test is effective! ! !

insert image description here

Error report

insert image description here
java.lang.NoClassDefFoundError exception

In daily Java development, we often encounter errors like java.lang.NoClassDefFoundError, and 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 is easy for us to confuse java.lang.NoClassDefFoundError and java.lang.ClassNotfoundException. In fact, these two errors are completely different. We often spend time trying to solve this problem in some other way, without really understanding the cause of this error. This article is to unravel some of the secrets of NoClassDefFoundError by sharing the experience of solving NoClassDefFoundError error handling. The error of NoClassDefFoundError is not unsolvable or difficult to solve, but the manifestation of this error is easy to confuse other Java developers. Let's analyze why NoClassDefFoundError occurs and how to solve it.

Error reason

The NoClassDefFoundError error occurs because the Java virtual machine can find the appropriate class at compile time, but cannot find the appropriate class at runtime. For example, when we want to call a method of a class or access a static member of this class at runtime, and find that the class is not available, the Java virtual machine will throw a NoClassDefFoundError error. The difference with ClassNotFoundException is that this error occurs only when the corresponding class needs to be loaded unsuccessfully at runtime, not at compile time. Many Java developers easily confuse these two mistakes here.

A brief summary is that NoClassDefFoundError occurs when the corresponding class is available at compile time, and the error caused by the corresponding class being unavailable in the Java classpath path at runtime. When a NoClassDefFoundError error occurs, you can see the following error log:

Exception in thread "main" java.lang.NoClassDefFoundError

The error message clearly indicates that the main thread cannot find the specified class, and this main thread may be the main thread or other sub-threads. If an error occurs in the main thread, the program will crash or stop, and if it is a child thread, the child thread stops and other threads continue to run.

The difference between NoClassDefFoundError and ClassNotFoundException
We are often confused by java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, although they are both related to the Java classpath, they are completely different. NoClassDefFoundError occurs when the JVM is running dynamically. According to the class name you provide, find the corresponding class in the classpath to load, but when it cannot find this class, a java.lang.NoClassDefFoundError error occurs, and ClassNotFoundException is An error occurs when the corresponding class cannot be found in the classpath at compile time. ClassNotFoundException is easier to solve than NoClassDefFoundError because we know that an error occurs at compile time, and it is entirely due to environmental problems. And if you are working in a J2EE environment and get a NoClassDefFoundError exception, and the corresponding wrong class does exist, it means that this class may not be visible to the class loader.

Solution

insert image description here
According to the previous article, it is obvious that the NoClassDefFoundError error is because the class loader cannot find the class to be loaded in the classpath at runtime, so we need to load the corresponding class into the classpath, or check why the class is not available in the classpath , this could happen for the following reasons:

The corresponding Class is not available in the java classpath.
You may run your program with the jar command, but the class is not defined in the classpath attribute in the manifest file of the jar file. Maybe the
startup script of the program overwrites the original classpath environment variable
because of NoClassDefFoundError It is a subclass of java.lang.LinkageError, so it may be caused by the unavailability of the original class library that the program depends on.
Check the log file for errors such as java.lang.ExceptionInInitializerError. NoClassDefFoundError may be caused by static initialization failure
If you work in a J2EE environment, there are multiple different class loaders, which may also cause NoClassDefFoundError.
Let's look at some examples of how we can solve NoClassDefFoundError when it occurs.

NoClassDefFoundError solution example

When a jar file is missing, or the jar file is not added to the classpath, or the file name of the jar changes, it will cause a java.lang.NoClassDefFoundError error.
When the class is not in the classpath, it is difficult to know exactly this situation, but if you print out System.getproperty("java.classpath") in the program, you can get the classpath that the program actually runs and specify clearly when you think the program is normal
. The running -classpath parameter, if the program can run normally after being added, it means that the classpath of the original program has been overwritten by others.
NoClassDefFoundError may also be caused by static initialization module errors of the class. When your class performs some static initialization module operations, if the initialization module throws an exception, other classes that depend on this class will throw NoClassDefFoundError errors. If you check the program log, you will find some java.lang.ExceptionInInitializerError error logs, ExceptionInInitializerError errors will cause java.lang.NoClassDefFoundError: Could not initialize class, as in the following code example:

/**
 * 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 throw NoClassDefFoundError
            }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.<clinit>(NoClassDefFoundErrorDueToStaticInitFailure.java:35)
    ... 1 more
java.lang.NoClassDefFoundError: Could not initialize class testing.User
    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)


Read more: http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz3dqtbvHDy

Since NoClassDefFoundError is a subclass of LinkageError, and LinkageError errors will occur when relying on other classes, so if your program depends on the native class library and the required dll does not exist, java.lang.NoClassDefFoundError may appear. This kind of error may also throw exceptions such as java.lang.UnsatisfiedLinkError: no dll in java.library.path Exception Java. The solution is to put the dependent class library and dll together with your jar package.
If you use the Ant build script to generate the jar file and manifest file, make sure the Ant script gets the correct classpath value and write it to the manifest.mf file.
Jar file permission issues can also cause NoClassDefFoundError if your program runs on something like linux For such a multi-user operating system, you need to assign the permissions of your application-related resource files, such as Jar files, class library files, and configuration files, to the user group to which the program belongs. If you use a jar shared by multiple users and different programs When installing packages, permissions issues can easily arise. For example, if your program does not have permission to access the jar package of other users' application permissions, it will cause a java.lang.NoClassDefFoundError error.
Programs based on XML configuration may also cause NoClassDefFoundError errors. For example, most Java frameworks like Spring and Struts use xml configuration to obtain corresponding bean information. If you enter a wrong name, the program may load other wrong classes and cause a NoClassDefFoundError exception. When we use the Spring MVC framework or the Apache Struts framework, Exception in thread “main” java.lang.NoClassDefFoundError often occurs when deploying War files or EAR files.
In a J2EE environment with multiple ClassLoaders, NoClassDefFoundError errors are prone to occur. Since J2EE does not specify a standard class loader, the class loader used depends on different containers such as Tomcat and WebLogic, and WebSphere loads different components of J2EE such as War packages or EJB-JAR packages. For more information about class loaders, please refer to this article How Class Loaders Work.

In summary, class loaders are based on three mechanisms: delegation, visibility, and singleness. The delegation mechanism refers to handing over the request to load a class to the parent class loader. If the parent class loader cannot find or load the class , then load it again. The principle of visibility is that the subclass loader can see all the classes loaded by the parent class loader, while the parent class loader cannot see the classes loaded by the subclass loader. The principle of singleness means that only one class is loaded once, which is ensured by the delegation mechanism that the child class loader will not load the class loaded by the parent class loader again. Now assume 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 sub-ClassLoader that loads the EJB-JAR ClassLoader. When the code in the EJB-JAR references the User class, the Classloader that loads all classes in the EJB-JAR cannot find this class, because this class has been loaded by the subloader WAR classloader of the EJB-JAR classloader.

The result of this will be a NoClassDefFoundError exception for the User class, and if the User class exists in both JAR packages, if you use the equals method to compare objects of the two classes, a ClassCastException exception will appear because the two are different Classes loaded by classloaders cannot be compared.

Sometimes there will be errors like Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/tools/javac/Main. This error indicates that your Classpath, PATH or JAVA_HOME is not installed correctly or that the JDK is not installed correctly. The solution to this problem is to reinstall your JDK.

When Java performs linking operations, it may also cause NoClassDefFoundError. For example, in the previous script, if we delete the compiled file of User after the compilation is completed, and then run the program, you will directly get NoClassDefFoundError at this time, and the error message only prints the name of the User class.

java.lang.NoClassDefFoundError: testing/User
    at testing.NoClassDefFoundErrorDueToStaticInitFailure.main(NoClassDefFoundErrorDueToStaticInitFailure.java:23)

Now we know how to face the NoClassDefFoundError exception and resolve it.

Welfare

6 technical books will be sent home every week
due to the limited time and energy of the blogger, and there are too many private messages every day, so it is impossible for every fan to reply in time. You
can enter the community skirt or add the blogger’s WeChat
and click the link below
http:/ /t.csdn.cn/6kInJ

Guess you like

Origin blog.csdn.net/weixin_50843918/article/details/129666631