如何在Java中为命令行参数创建标志?

我有一个25个应用程序的枚举和一些环境的枚举。

现在有了我拥有的代码,我可以不传递参数,它可以在所有环境中运行所有应用程序(这就是我想要的),或者我可以按顺序传递一个应用程序和一个环境,它将运行它。 我需要通过像-app app1 app2 app3 … -env env1 env2这样的东西来传递应用列表……

我以前从未使用过标志或尝试过解析过一系列命令。 这是代码的一部分。 我认为if是好的但是其他地方是我需要帮助的地方。

public static Application chooseAppTest(String[] args) { Application application = null; switch (Application.valueOf(args[0])) { case ACCOUNTINVENTORY: new AccountInventory(Environment.valueOf(args[1])); AccountInventory.accountInventoryDatabaseTests(testResults); break; public static void main(String[] args) { // run tests and collect results if (args.length == 0) { LogIn.loginTest(testResults); DatabaseTest.testResults(testResults); LinkTest.linkTests(testResults); } else { // First choose application, then choose environment Application.chooseAppTest(args); } 

尽管这可能不会直接回答您的问题,但我强烈建议您使用库。 一些广泛使用的选项:

  1. Commons CLI – http://commons.apache.org/proper/commons-cli/
  2. JCommander – http://jcommander.org/
  3. JOpt-Simple – http://pholser.github.io/jopt-simple/
  4. ArgParse4J – http://argparse4j.sourceforge.net/

毕竟,“ 生命太短,无法解析命令行参数 ”。 作为示例(使用JCommander ),您只需要通过注释定义参数:

 //class MyOptions @Parameter(names = { "-d", "--outputDirectory" }, description = "Directory") private String outputDirectory; 

然后使用以下方法解析bean:

 public static void main(String[] args){ MyOptions options = new MyOptions(); new JCommander(options, args); }