Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java using "-cp" and "-jar" together

Tags:

java

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?

like image 376
Peter Avatar asked Aug 21 '12 02:08

Peter


2 Answers

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.

like image 11
lucasweb Avatar answered Oct 16 '22 21:10

lucasweb


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.

like image 6
Logan Avatar answered Oct 16 '22 19:10

Logan