How do you parse arguments for a java program?

前端 未结 3 1575
生来不讨喜
生来不讨喜 2021-01-26 13:41

I\'m making a Selenium WebDriver java program. I have 25 application and 4 environments. I need to be able to pass something like -app app1 app2 app3 ... appn -env env1 env2 env

相关标签:
3条回答
  • 2021-01-26 14:17

    It is not necessary or advantagious to use recursion. You can read all the arguments into an array and process them from there. Other than that, I'm not sure how you would proceed. With the arguments arranged in this way, how do you know which environment goes with which application?

    0 讨论(0)
  • 2021-01-26 14:23

    As Elliott commented, have you looked at Apache Commons CLI? It's a command line parser.

    0 讨论(0)
  • 2021-01-26 14:30

    I don't think recursion is needed. You can do something like this:

    public static void main (String[] args)
    {
        List<String> apps = new LinkedList<>();
        List<String> envs = new LinkedList<>();
        List<String> 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);
    }
    
    0 讨论(0)
提交回复
热议问题