Apache Commons CLI无法按预期进行解析? [英] Apache commons CLI not parsing as expected?

查看:97
本文介绍了Apache Commons CLI无法按预期进行解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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库来解析命令行args,但是它似乎没有按预期进行解析.不知道我在这里想念什么吗?

I am using Apache commons cli library to parse command line args however it doesn't seem to parse as expected. Not sure what I am missing here?

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

I invoked in many different way just to see if it works and the below is one of them java -jar dbservice.jar --host localhost --port 7514. What is the right way to invoke anyway? I dont see that in the documentation

推荐答案

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

In order for the Option to accept an argument, the hasArg(true) must be passed to the builder. For each of the options, add a ".hasArg(true)". Modifying your code with this argument and running a test case resulted in the expected output.

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

这篇关于Apache Commons CLI无法按预期进行解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆