Apache commons CLI 没有按预期解析?

Apache commons CLI not parsing as expected?

public static void main(String[] args) {

    Options options = new Options();
    Option hostOption = Option.builder("h")
            .longOpt("host")
            .required(false)
            .build();

    Option portOption = Option.builder("p")
            .longOpt("port")
            .required(false)
            .type(Number.class)
            .build();

    Option serviceNameOption = Option.builder("n")
            .longOpt("service_name")
            .required(false)
            .build();

    options.addOption(hostOption);
    options.addOption(portOption);
    options.addOption(serviceNameOption);

    String serviceName = "dbservice"
    String host = "localhost";
    int port = 7512;
    CommandLineParser parser = new DefaultParser();
    Server server = new Server();
    try {
        CommandLine cmd = parser.parse(options, args);
        if(cmd.hasOption("host")) {
            host = cmd.getOptionValue("host");
            System.out.println(host); //gets in here but prints null
        }
        if (cmd.hasOption("port")) {
            port = ((Number)cmd.getParsedOptionValue("port")).intValue();
            System.out.println(port); // gets in here but throws a null pointer exception

        }
        if (cmd.hasOption("service_name")) {
            serviceName = cmd.getOptionValue("service_name");
            System.out.println(serviceName); // gets in here but prints null
        }
    } catch(Exception e) {}
 }

我正在使用 Apache commons cli 库来解析命令行参数,但它似乎没有按预期进行解析。不确定我在这里缺少什么?

我以多种不同的方式调用只是为了看看它是否有效,下面是其中之一 java -jar dbservice.jar --host localhost --port 7514。无论如何调用的正确方法是什么?我在文档中没有看到

为了让 Option 接受参数,必须将 hasArg(true) 传递给构建器。对于每个选项,添加一个“.hasArg(true)”。使用此参数和 运行 测试用例修改您的代码会产生预期的输出。

    Option hostOption = Option.builder("h")
        .longOpt("host")
        .required(false)
        .hasArg(true)
        .build();

对于初次使用的用户,hasArg() 令人困惑,默认情况下,您会假设在不指定 hasArg() 的情况下,至少会采用一个参数来创建选项。在没有 hasArg() 的情况下传递值 '--opt val' 会默默地忽略 val,就好像没有传递任何内容一样,好吧,如果没有指定 hasArg() 那么它应该失败,因为传递了一些东西而不是忽略了。也许,应该有一个严格的模式?