How to Add Libraries to a JAR
Most JARs, no matter whether they contain an executable program or a library, require other libraries to run. Those dependencies are usually contained in JARs as well. So how can you make sure that your JAR has all required JARs in its CLASSPATH? There are three common solutions for executable JARs.
Solution 1: Using the Class-Path Attribute
The Class-Path attribute of the manifest file allows you to state a list of JARs that the Java runtime should put into its classpath. So basically your program consists of several JARs, one executable for the program itself and one JAR for each library.
This example shows a manifest file with several dependencies:
Manifest-Version: 1.0 Main-Class: com.jarfiller.example.MainClass Class-Path: log4j.jar mail.jar
Note that your IDE may be able to create such a manifest and package your libraries automatically. For example, Eclipse can do this since version 3.5 (export your project as 'Runnable JAR file' and select the appropriate option).
Solution 2: Unpack Library JARs into a Single JAR
A nifty solution to the problem is to unpack all JARs you depend on and put them all into a single JAR. This works most of the time, but with some JARs, such as Service Providers, it won't (more).
There are several tools that allow you to do this to various extends (e.g. they may not merge the manifests of the JARs correctly). Recent Eclipse versions can repack executable JARs. Just export the project into a 'Runnable JAR file' and select the right option.
Ant also allows you to unpack JARs into a single JAR using the jar task.
Solution 3: Call java with all JARs in the CLASSPATH
Another common solution is to write a script or batch file that puts all JARs into the classpath and then starts the application. This also allows you to add other arguments to the Java runtime (such as an increased heap) and state the main class (so you don't need a special manifest). Then you start the application like this:
C:\Users\tim\tmp>java -cp jarfiller-example.jar;log4j.jar;mail.jar com.jarfiller.example.MainClass
Dependencies for Library
Most libraries also depend on other libraries. Theoretically you could apply Solution 1 or Solution 2 to a library. This would be rather unusual though. Common practice is to state your dependencies somewhere in the documentation (or just have a directory containing dependencies) and let the library's user take care of putting them into the classpath. Do not apply the solutions above to libraries.
The main reason is that the you (or, rather, the library's user) needs to be sure to have every library only once in the classpath. With Solution 1, two JARs could depend on the same library, but use different names for it, and you end up with including the library twice. With Solution 2, several JARs could contain the same library. Both solutions get especially messy when different versions of the same library are involved.