Tuesday, June 18, 2013

java.lang.NoClassDefFoundError

Description and Symptoms

Exception in thread "main" java.lang.NoClassDefFoundError is one of the most complex problems that you can face when developing Java applications. This error is thrown by the JVM at runtime when it is unable to locate a particular Java class from the current Thread context class loader.

Sample Error

java.lang.NoClassDefFoundError: Could not initialize class org.ph.javaee.training2.ClassA
       at org.ph.javaee.training2.NoClassDefFoundErrorSimulator.main(NoClassDefFoundErrorSimulator.java:32)


java.lang.ExceptionInInitializerError
       at org.ph.javaee.training2.NoClassDefFoundErrorSimulator.main(NoClassDefFoundErrorSimulator.java:23)
Caused by: java.lang.IllegalStateException: ClassA.initStaticVariable(): Internal Error!
       at org.ph.javaee.training2.ClassA.initStaticVariable(ClassA.java:37)
       at org.ph.javaee.training2.ClassA.<clinit>(ClassA.java:16)
       ... 1 more

Possible causes

  • Missing Java class and/or JAR file(s) from your Java runtime classpath.
  • Failure of a static variable or initializer block at class loading time.
  • Packaging problem of your application or third part API causing a mixed-up of class loading between the parent and child class loaders.
  • Wrong Class loader delegation model based on your application and packaging requirements.

Troubleshooting and solutions

  • First identify the Java class the JVM is complaining about.
  • Check for a simple root cause first: wrong Java runtime classpath.
  • If the problem persists, verify if the affected Java class contains static initializers e.g. static variable and/or static block initializer. Look for any failure at class loading time.
  • Once the above items are ruled out, perform an assessment of your application runtime class loader delegation model and look for any packing problem.

References and Case Studies