Fix Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Mehvish Ashiq Jan 30, 2023 Aug 01, 2022
  1. Java Program With the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  2. Possible Causes for Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
  3. Solution to Eradicate the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error
Fix Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Today, we will learn about another runtime error: the java.lang.noclassdeffounderror: could not initialize class. First, we will go through a Java program having this error which will lead to the discussion about possible reasons and figure out which line of code is causing this error.

Finally, we will also learn about the solution to eliminate this error.

Java Program With the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Example Code:

public class PropHolder {
  public static Properties prop;

  static {
    // write code to load the properties from a file
  }
}

Example Code:

import java.util.Properties;

public class Main{
    public static void main(String[] args){
        //set your properties here
        //save the properties in a file
        // Referencing the PropHolder.prop:
  		Properties prop = PropHolder.prop;
        //print the values of all properties
    }
}

Here, we have two .java classes named PropHolder and Main. The PropHolder class loads the properties from the specified file while the Main class sets them and saves them into a file.

It also references the prop variable of the PropHolder class to print the values of all properties.

This Java code works fine when we run it on our local machine, but it does not work when deployed on a Linux Server with some script. Why is it so? Let’s figure out the reasons.

Possible Causes for Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

Firstly, remember that getting the java.lang.NoClassDefFoundError does not only mean our class is missing. If that is so, we will get the java.lang.ClassNotFoundException.

It also does not mean that the bytecode (.class) is missing (in that case, we would get an error like this java.lang.NoClassDefFoundError: classname).

So, the java.lang.noclassdeffounderror: could not initialize class error by our server means it cannot locate the class file. It can be caused by different reasons that are listed below.

  1. The issue can be in the static block (also called a static initializer). It’d appear with an uncaught exception, occur & propagated up to an actual ClassLoader trying to load a class.

  2. If the exception is not due to the static block, it can be while creating a static variable named PropHolder.prop.

  3. Possibly, the Class is not available in the specified Java CLASSPATH.

  4. We might have executed our Java program using the jar command while the Class was not defined in the ClassPath attribute of the MANIFEST file.

  5. This error can be caused by a start-up script that overrides the CLASSPATH environment variable.

  6. Another reason could be missing a dependency. For instance, the native library might not be available because NoClassDefFoundError is the child class of java.lang.LinkageError.

  7. We can also look for the java.lang.ExceptionInInitializerError in our log file because there is a possibility that the NoClassDefFoundError was occurring due to the failure of static initialization.

  8. If one of you is working in the J2EE environment, then the Class’s visibility in different ClassLoaders can cause the java.lang.NoClassDefFoundError error.

  9. Sometimes, it causes due to JRE/JDK version error.

  10. It can also occur when we compile something on our machine with, let’s say, OpenJDK version 8.x.x. We push/commit, but someone else has configured its JAVA_HOME to some 11.x JDK version.

    Here, we can get ClassNotFoundError, NoClassDefFoundError, etc. So, it is better to check what JDK the program has been compiled with.

Solution to Eradicate the Java.Lang.NoClassDefFoundError: Could Not Initialize Class Error

In our case, the ClassLoader ran into the error while reading the class definition when it was trying to read the class. So, putting a try-catch block inside the static initializer will solve the issue.

Remember, if we are reading some files there, then it would differ from our local environment.

Example Code:

//import libraries
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

//PropHolder Class
public class PropHolder {
    //static variable of type Properties
    public static Properties prop;

    //static block, which loads the properties
    //from the specified file
    static {
        try {
            InputStream input = new FileInputStream("properties");
            prop = new Properties();
            prop.load(input);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(PropHolder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PropHolder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//end static block
}//end PropHolder class

In the above class, we created a static variable named prop of type Properties, which we use in the static block. Inside the static block, we created an object of the FileInputStream, which obtains the input bytes from a specified file in the file system.

Next, we initialized the prop variable by calling the constructor of the Properties class, which is used to load the properties from a specified file. Remember, this static block only gets executed once we run the application.

Example Code:

//import libraries

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

//Main Class
public class Main {

    //main()
    public static void main(String[] args) {
        /*
        instantiate the Properties class, set various
        properties and store them in a given file
         */
        Properties prop = new Properties();
        prop.setProperty("db.url", "localhost");
        prop.setProperty("db.user", "user");
        prop.setProperty("db.password", "password");
        try {
            OutputStream output = new FileOutputStream("properties");
            prop.store(output, null);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(PropHolder.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(PropHolder.class.getName()).log(Level.SEVERE, null, ex);
        }

        /*
        reference the `PropHolder.prop` to access the values of
        the properties that we set previously
         */
        Properties obj = PropHolder.prop;
        System.out.println(obj.getProperty("db.url"));
        System.out.println(obj.getProperty("db.user"));
        System.out.println(obj.getProperty("db.password"));
    }//end main()
}//end Main

In the Main class, we instantiate the Properties class to set values for various properties and save them in the specified file. Next, we reference the PropHolder.prop to access the values of db.url, db.user, and db.password properties and print them on the program output console as follows.

OUTPUT:

localhost
user
password
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - Java Error