如何确保在Apache Commons CLI中提供所有参数?

时间:2022-02-04 17:12:08

I don't see a standard way of checking if all Options are provided in a String[] input to apache's CLI library . That is - my options are all REUIRED at the command line, otherwise, i want an exception to throw.

我没有看到一种标准方法来检查是否所有选项都在String []输入中提供给apache的CLI库。也就是说 - 我的选项在命令行都是REUIRED,否则,我想抛出异常。

Im trying the following as a workaround, but getting a Nullpointer exception in the if statement...

我尝试以下作为解决方法,但在if语句中获取Nullpointer异常...

PosixParser p = new PosixParser();
        CommandLine cli=p.parse(options,args);
        for(Object o : options.getOptions())
        {
            Option op = (Option)o;
            if(cli.getOptionValue(op.getName()))
            throw new ParseException("Missing argument ! " + op.getArgName() + ":"+op.getDescription());
    }

UPDATE ON THIS : the getOpt() method seems to provide the arguments short name.

更新:getOpt()方法似乎提供了参数短名称。

However, if I replace op.getName() with opt.getLongName()... it works !

但是,如果我用op.getLongName()替换op.getName()......它可以工作!

In any case.. I have 2 questions :

无论如何......我有两个问题:

1) Why would an option have a null name, yet a non-null longName ?
2) Is there a way to simply ensure that all options are provided the String[] ? For example, I would like to call :

1)为什么一个选项有一个空名称,但是一个非null的longName? 2)有没有办法简单地确保所有选项都提供String []?例如,我想打电话:

  if(! options.isAllProvided())
     throw new ParseException("You are missing some options ! " + StringUtils.join(userInputArray,','));

1 个解决方案

#1


9  

Here's how you can set an Option to be required:

以下是如何设置所需的选项:

Option logfile = OptionBuilder.withArgName( "file" )
            .isRequired() // make it required
            .hasArg()
            .withDescription(  "use given file for log" )
            .create( "logfile" );

(I don't think there's an easy way to make all Options required in one step)

(我认为没有一种简单的方法可以一步完成所有选项)

#1


9  

Here's how you can set an Option to be required:

以下是如何设置所需的选项:

Option logfile = OptionBuilder.withArgName( "file" )
            .isRequired() // make it required
            .hasArg()
            .withDescription(  "use given file for log" )
            .create( "logfile" );

(I don't think there's an easy way to make all Options required in one step)

(我认为没有一种简单的方法可以一步完成所有选项)