Selecting main class in a runnable jar at runtime

孤者浪人 提交于 2019-11-28 21:09:05

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.

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!