Java 在运行时选择可运行 jar 中的主类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2023506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:42:29  来源:igfitidea点击:

Selecting main class in a runnable jar at runtime

javajarexecutable-jar

提问by Tomasz

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.

我在应用程序中有两个主要类。当我将它打包到一个可运行的 jar(使用 Eclipse 导出功能)时,我必须选择一个默认的主类。

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

有没有办法在运行时从 jar 访问非默认主类?

采纳答案by Jeremy Raymond

You can access both via java -cp myapp.jar com.example.Main1and 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.

您可以通过java -cp myapp.jar com.example.Main1和访问java -cp myapp.jar com.example.Main2。jar 中的默认主类用于通过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.MyClassinside of the jar manifest META-INF/MANIFEST.MFin side of the jar file.

有关更多详细信息,请参阅JAR_(file_format)。当您在 Eclipse 中选择主类时,这就是设置的内容:Main-Class: myPrograms.MyClassMETA-INF/MANIFEST.MFjar 文件一侧的 jar 清单内。

回答by BalusC

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.lengthand so on)

(不要忘记自己添加明显的检查,例如args.length等等)

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.

但是,如果设计得当,这会使main()其他类的方法变得多余。例如

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 Actioninterface with a void execute()and get hold of them in a Map:

为了进一步抽象(摆脱 if/else 块),您可以考虑让它们Action使用 a实现一些接口并在 a 中void execute()获取它们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();
}