Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple runnable classes inside JAR, how to run them?

Tags:

java

jar

I'm having problems with running multiple different classes from one JAR file. I know that I can set one of the classes inside JAR to by Main class that will be run after command java -jar myjar.jar, but what I want is something like:

java -jar myjar.jar MyClass 

Is it possible to do this that way, or do I have to create multiple JAR (each for one runnable class), or is it better to create 'manager' class that will run my other classes passing to them command line arguments?
I was looking for documentation or reference, but I couldn't find any.

like image 337
wlk Avatar asked Oct 20 '10 09:10

wlk


People also ask

Can a jar have two main classes?

Jar files can contain only one Main-Class attribute in the manifest, which means a jar can contain only one mainClassName.


2 Answers

The executable Jar file format only allows you to specify one main class. In order for you to be able to execute different applications, you'll need to either create a "manager" as you suggest, or to use the classpath instead:

java -cp myjar.jar MyClass 

However, this approach will ignore the classpath you have configured in the Jar's manifest file.

like image 178
iggymoran Avatar answered Sep 24 '22 09:09

iggymoran


you will have to use:

java -cp myjar.jar MyClass 

and

java -cp myjar.jar OtherMainClass 
like image 35
Gareth Davis Avatar answered Sep 22 '22 09:09

Gareth Davis