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?
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use
-cp
or specify the main class. In your case it would contain lines like this:Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the
java -jar MyJar.jar
.Then execute it with
You can do these in unix shell:
You can do these in windows powershell:
When you specify
-jar
then the-cp
parameter will be ignored.From the documentation:
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:
lib
directory into the manifest (you can use relative paths there)-cp
:java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main
Run a jar file and specify a class path like this:
jar_name.jar
is the full name of the JAR you want to executelibs/*
is a path to your dependency JARscom.test.App
is the fully qualified name of the class from the JAR that has themain(String[])
methodThe jar and dependent jar should have execute permissions.