简体   繁体   English

您如何解析Java程序的参数?

[英]How do you parse arguments for a java program?

I'm making a Selenium WebDriver java program. 我正在制作一个Selenium WebDriver Java程序。 I have 25 application and 4 environments. 我有25个应用程序和4个环境。 I need to be able to pass something like -app app1 app2 app3 ... appn -env env1 env2 envn 我需要能够通过-app app1 app2 app3 ... appn -env env1 env2 envn之类的东西

I need to be able to pass either, neither or both arguments. 我需要既可以传递任何一个参数,也可以不传递两个参数。 Right now I have it being able to pass one app and one env in that order but I need to be able to do it in either order and with the either neither or both possibility. 现在,我可以按此顺序传递一个应用程序和一个环境,但是我需要能够按任一顺序进行操作,并且不能同时执行两种操作。 Here's what I have so far. 到目前为止,这就是我所拥有的。 With this I can either pass no arguments and runs every app for every environment (which is what I want) or I can pick app1 env1 in that order for that specific test. 有了这个,我要么不传递任何参数,就为每个环境(这就是我想要的)运行每个应用程序,要么我可以按顺序为特定测试选择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);
    }

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);
}

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? 通过这样排列参数,您如何知道哪个环境与哪个应用程序一起使用?

As Elliott commented, have you looked at Apache Commons CLI ? 正如Elliott所说,您是否看过Apache Commons CLI It's a command line parser. 这是一个命令行解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM