你如何在 Java 中为命令行参数制作标志?

use*_*792 0 java command-line-arguments

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

现在使用我拥有的代码,我可以不传递任何参数并在所有环境中运行所有应用程序(这是我想要的),或者我可以按顺序传递一个应用程序和一个环境,它将运行它。我需要能够通过执行类似 -app app1 app2 app3 ... -env env1 env2 ...

我以前从未使用过标志,也从未尝试过解析命令数组。这是代码的一部分。我认为 if 很好,但 else 是我需要帮助的地方。

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);
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*des 5

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

  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;
Run Code Online (Sandbox Code Playgroud)

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

public static void main(String[] args){
    MyOptions options = new MyOptions();
    new JCommander(options, args);
}
Run Code Online (Sandbox Code Playgroud)