Run a JAR file from the command line and specify classpath

SnakeDoc picture SnakeDoc · Aug 24, 2013 · Viewed 227.7k times · Source

I've compiled a JAR file and specified the Main-Class in the manifest (I used the Eclipse Export function). My dependencies are all in a directory labeled lib. I can't seem to get a straight answer on how to execute my JAR file while specifying it should use the lib/* as the classpath.

I've tried:

]$ java -jar -cp .:lib/* MyJar.jar
]$ java -cp .:lib/* -jar MyJar.jar
]$ java -cp .:lib/* com.somepackage.subpackage.Main

etc...

Each gives an error saying:

Error: Could not find or load main class ....

or gives the NoClassDefFoundError indicating the libraries are not being found.

I even tried remaking the JAR file and included the lib directory and contents, but still no dice...

How can I execute a JAR file from the command line and specify the classpath to use?

Answer

a_horse_with_no_name picture a_horse_with_no_name · Aug 24, 2013

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main