简体   繁体   中英

How do I use manifest.mf class-path for alternative main in same jar?

I have created an executable jar file that contains two main classes. All libraries are included in the jar and the main Main-Class works fine when executing like this:

java -jar MyApplication.jar

But when I try to run the other main class like this:

java -cp MyApplication.jar my.other.mainClass

It does not include the classpath of the manifest.mf and it can not find the libraries that are in the jar file.

Is there a simple way so that the other main class can use the classpath from the manifest.mf? or should I create two separate executable jars?

You could write a class that invokes the main method of whatever class is passed as its first argument using Reflection - and configure this as the Main-class in your jar. This way you can invoke multiple main methods from the same jar with java -jar file.jar my.other.mainClass

Is there a simple way so that the other main class can use the classpath from the manifest.mf? or should I create two separate executable jars?

The JAR manifest classpath is only used if you use -jar option, and conversely the command line argument is only interpreted as a classname if -jar is NOT used. You cannot mix the two approaches.

However, this doesn't mean you have to create a second JAR file. For instance, you could write a simple shell script to launch the JVM using the classpath copied from the manifest and the secondary entry point classname.

Are you sure your problem is with libraries within the jar? What version of java are you using?

I suggest you try the following:

java -cp MyApplication.jar <add external libraries here> my.other.mainClass

So you only need to add paths to classes that are not already in the jar. You can use wild cards to shorten the list.

Here is another interesting option, Enable your unrunnable JARs to run with the java -jar command . It describes how to select a main class in the jar file and make another runnable copy.

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