你如何解析java程序的参数?

我正在制作Selenium WebDriver java程序。 我有25个应用程序和4个环境。 我需要能够传递类似-app app1 app2 app3 … appn -env env1 env2 envn

我需要能够传递其中一个,两个或两个参数。 现在我能够按顺序传递一个应用程序和一个环境但是我需要能够以任何顺序执行它,并且既不可能也不可能。 这是我到目前为止所拥有的。 有了这个,我可以不传递参数并为每个环境运行每个应用程序(这是我想要的)或者我可以按照该特定测试的顺序选择app1 env1。

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; if (args.length == 0) { LogIn.loginTest(testResults); DatabaseTest.testResults(testResults); LinkTest.linkTests(testResults); } else { // First choose application, then choose environment Application.chooseAppTest(args); } 

我认为不需要递归。 你可以这样做:

 public static void main (String[] args) { List apps = new LinkedList<>(); List envs = new LinkedList<>(); List current = null; // parse arguments for (String arg : args) { if (arg.equals("-app")) current = apps; else if (arg.equals("-env")) current = envs; else if (current != null) // add argument current.add(arg); } // parsing finished Application.doSomethingWith(apps, envs); } 

使用递归是没有必要或没有意义的。 您可以将所有参数读入数组并从那里处理它们。 除此之外,我不确定你会怎么做。 通过这种方式排列参数,您如何知道哪个环境与哪个应用程序相关?

正如Elliott评论的那样,你看过Apache Commons CLI吗? 它是一个命令行解析器。