tags:

views:

43

answers:

5

Hello,
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.

+3  A: 

you will have to use:

java -cp myjar.jar MyClass

and

java -cp myjar.jar OtherMainClass
Gareth Davis
+2  A: 

You do it like this:

java -cp myjar.jar MyClass

i.e. put the JAR into the classpath, then any class with a main method can be run by specifying its fully qualified name. The -jar option only exists as a shortcut to use the information in the JAR's manifest instead (which can also include other JARs in the classpath as well as specify the main class).

Michael Borgwardt
+1  A: 

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.

iggymoran
Ignorig classpath inside manifest was one of my concerns. But I have tested this solution, and it seems to work (but I don't know why really, because I have set classpath inside manifest)
Wojtek
It's because this form of startup does not bother reading the manifest. Only the -jar form reads the manifest.
Cameron Skinner
A: 

Jar files can contain only one Main-Class attribute in the manifest, which means java -jar myjar.jar can only start one class.

You can start other runnable classes with

java -cp myjar.jar OtherClass

but that won't support users double-clicking on the jar file.

Depending on how skilled your users are, maybe the command line is OK for them. If not, you can create a script for each runnable class or one script that takes arguments to choose the right class.

Cameron Skinner
+1  A: 

This doc will help you.

PeterMmm