17 September 2009

Exception in thread "main" java.lang.NoClassDefFoundError: ClassName

The exception "Exception in thread "main" java.lang.NoClassDefFoundError" normally happens when the class is not correctly defined in the classpath. However, it can also happens when incorrectly launched using java ClassName.class. Following are some scenarios when this problem can happen:

1. Class launched with .class file extension

When launching a class using java ClassName adding .class as part of the class name, this exception is thrown because java considers the name of the class as ClassName.class, so cannot find the class. See below an example.

Wrong

java ClassName.class

Following execption is thrown because java cannot find the class
"Exception in thread "main" java.lang.NoClassDefFoundError: ClassName"

Correct

java ClassName

In this case the class if found, so no exception is thrown.


2. jar file classpath

This error also happened when launching a jar file using java -jar ClassName as displayed in the exception below:


Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Logger
        at com.sds.pev.util.ConfParamBase.(ConfParamBase.java:33)
        at SendMessageToTCPServer.main(SendMessageToTCPServer.java:19)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Logger
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClassInternal(Unknown Source)
        ... 2 more

This exception means that the Log4j jar files was not found. Even adding the jar to the Windows classpath this error was happening. The way how I solved the problem was adding the classpath tag in the Manifest file, as described below:

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 11.3-b02 (Sun Microsystems Inc.)
Main-Class: SendMessageToTCPServer
Class-Path: log_log4j-1.2.15.jar

No comments:

Post a Comment