Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting main class in a runnable jar at runtime

I have two main classes in the app. When I package it to a runnable jar (using Eclipse export function) I have to select a default main class.

Is there a way to access the non-default main class from the jar at runtime?

like image 259
Tomasz Avatar asked Jan 07 '10 20:01

Tomasz


People also ask

How do you set the main class in a running JAR?

We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …] As we can see, in this case, we'll have to include the main class name in the command line, followed by arguments.

Does a JAR file need a main method?

For a JAR file to run, the JAR itself must contain at least one class that has a runnable main method. Furthermore, the class with the main method must be listed as the main-class in the JAR's manifest file.

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

You can access both via java -cp myapp.jar com.example.Main1 and java -cp myapp.jar com.example.Main2. The default main class in the jar is for when you invoke your app via java -jar myapp.jar.

See JAR_(file_format) for more details. When you select the main class in Eclipse this is what gets set in: Main-Class: myPrograms.MyClass inside of the jar manifest META-INF/MANIFEST.MF in side of the jar file.

like image 64
Jeremy Raymond Avatar answered Sep 28 '22 10:09

Jeremy Raymond


Yes, it's possible. You can under each add another class with a main method for that which executes the desired class/method based on the argument.

E.g.

public static void main(String... args) {
    if ("foo".equals(args[0])) {
        Foo.main(args);
    } else if ("bar".equals(args[0])) {
        Bar.main(args);
    }
 }

(don't forget to add the obvious checks yourself such as args.length and so on)

Which you can use as follows:

java -jar YourJar.jar foo

If well designed, this can however make the main() method of the other classes superfluous. E.g.

public static void main(String... args) {
    if ("foo".equals(args[0])) {
        new Foo().execute();
    } else if ("bar".equals(args[0])) {
        new Bar().execute();
    }
 }

To abstract this more (to get rid of if/else blocks), you could consider to let them implement some Action interface with a void execute() and get hold of them in a Map:

private static Map<String, Action> actions = new HashMap<String, Action>();
static {
    actions.put("foo", new Foo());
    actions.put("bar", new Bar());
}

public static void main(String... args) {
    actions.get(args[0]).execute();
}
like image 32
BalusC Avatar answered Sep 28 '22 10:09

BalusC