Call “java -jar MyFile.jar” with additional classpath option

You use either -jar or -cp, you can’t combine the two. If you want to put additional JARs on the classpath then you should either put them in the main JAR’s manifest and then use java -jar or you put the full classpath (including the main JAR and its dependencies) in -cp and name the main class explicitly on the command line

java -cp 'MyProgram.jar:libs/*' main.Main

(I’m using the dir/* syntax that tells the java command to add all .jar files from a particular directory to the classpath. Note that the * must be protected from expansion by the shell, which is why I’ve used single quotes.)

You mention that you’re using Ant so for the alternative manifest approach, you can use ant’s <manifestclasspath> task after copying the dependencies but before building the JAR.

<manifestclasspath property="myprogram.manifest.classpath" jarfile="MyProgram.jar">
  <classpath>
    <fileset dir="libs" includes="*.jar" />
  </classpath>
</manifestclasspath>

<jar destfile="MyProgram.jar" basedir="classes">
  <manifest>
    <attribute name="Main-Class" value="main.Main" />
    <attribute name="Class-Path" value="${myprogram.manifest.classpath}" />
  </manifest>
</jar>

With this in place, java -jar MyProgram.jar will work correctly, and will include all the libs JAR files on the classpath as well.

Leave a Comment