tags:

views:

257

answers:

2

I have a Java Program that references a Jar File.

The Jar File is present in the same directory as the .class File but when I try to run the program from console, I get NoClassDefFound error :-(

Alternatively it runs Ok from Eclipse.

Why ?

+4  A: 

The java program will not automatically include JAR files in its class path. You add a JAR file to its class path via the -classpath option. For example:

java -classpath .;yourJarFile.jar your.MainClass

Eclipse is automatically adding the JAR file whenever you run the program.

Note: The -classpath option expects a semicolon (;) when running on Windows and a colon (:) otherwise.

Adam Paynter
I guess you are right. Now if the Jar File uses any other Jar File I should add that too?
Geek
Unfortunately, yes. http://en.wikipedia.org/wiki/Dependency_hell
Adam Paynter
http://en.wikipedia.org/wiki/JAR_hell#JAR_hell
Adam Paynter
Thanks mate. Dude can you give me an example of two Jar Files. ? On a unix system.
Geek
You just separate all the JAR file names with a colon (`:`) on a UNIX system:`java -classpath .:firstJarFile.jar:secondJarFile.jar your.MainClass
Adam Paynter
+1  A: 

JAR files are not automatically included in the classpath. You can add a Class-Path entry and a Main-Class entry to the to JAR file containing the main method that you wish to execute. Then you can execute your code like so:

java -jar yourJarFile.jar

See the JAR File Specification for more details.

or specify the classpath on the command line:

java -classpath lib1.jar:lib2.jar:yourJarFile.jar your.MainClass
NullPointerException