简体   繁体   中英

Java using “-cp” and “-jar” together

Earlier, I had just one jar file and the manifest was set up such that I can simply run my program as:

 java -jar MyApp.jar

Now, I have separated my functionality into two jar files - MyCore.jar and MyApp.jar.

The following command works:

java -cp "*" com.mycompany.mypackage.App

But I cannot get the following to work

java -cp "*" -jar MyApp.jar

I get a ClassNotFoundException.

I prefer using "-jar" switch. Is there a way to make it work?

As per the Java cli documentation you can not combine -cp and -jar in the same command

-jar Execute a program encapsulated in a JAR archive. The first argument is the name of a JAR file instead of a startup class name. In order for this option to work, the manifest of the JAR file must contain a line of the form Main-Class:classname. Here, classname identifies the class having the public static void main(String[] args) method that serves as your application's starting point. See the Jar tool reference page and the Jar trail of the Java Tutorial for information about working with Jar files and Jar-file mani- fests. When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored. Note that JAR files that can be run with the "java -jar" option can have their execute permissions set so they can be run without using "java -jar". Refer to Java Archive (JAR) Files.

In order to resolve this you will need to ensure the manifest in your application jar references both the Class that contains the main file and the classpath.

I have a Manifest.mf file like this.

Manifest-Version: 1.0
Main-Class: com.mycompany.mypackage.App
Class-Path: MyApp.jar MyCore.jar log4j.jar 

You can just add any jar files you need to the Class-Path line. Then as long as the jars are in the class path you can run the java -jar command without -cp.

Assuming both jar files are in the same folder and com.mycompany.mypackage.App is the main application class, try this command:

java -cp MyCore.jar;MyApp.jar com.mycompany.mypackage.App

It should work for you.

In case you insist on use of -jar switch ( why? ), then you need to have your manifest file modified, to add Class-Path key and specify path to all related jar files. It makes your application less flexible in case jar files are not packaged with your main app jar file.

Add a manifest that both specifies the class containing main() as well as the class-path. See Working with Manifest Files: Adding Classes to the JAR File's Classpath for more details.

Then the entire app. can be launched using -jar , without needing -cp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM