How do you make flags for command line arguments i

2019-02-16 02:27发布

I have an enum for 25 applications and an enum for some environments.

Right now with the code I have I can either pass no arguments and it runs all of the application in all of the environments(which is what I want) or I can pass one app and one environment in that order it will run that. I need to be able to pass a list of apps by doing something like -app app1 app2 app3 ... -env env1 env2...

I've never used flags before or tried parsing an array of commands before. Here's part of the code. I think the if is good but the else is where I need help.

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条回答
放荡不羁爱自由
2楼-- · 2019-02-16 02:55

Even though this might not directly answer your question, I strongly suggest that you use a library for that. Some widely used options:

  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/

After all, "life is too short to parse command line parameters". As an example (using JCommander), you just need to define your parameters through annotations:

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

And then parse your bean using:

public static void main(String[] args){
    MyOptions options = new MyOptions();
    new JCommander(options, args);
}
查看更多
登录 后发表回答