Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - Apache Commons CLI - option type and default value

How can I give a CLI Option a type - such as int or Integer? (Later, how can I get the parsed value with a single function call?)

How can I give a CLI Option a default value? Such that CommandLine.getOptionValue() or the function call mentioned above return that value unless one is specified on the command line?

question from:https://stackoverflow.com/questions/5585634/apache-commons-cli-option-type-and-default-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: Default values are now supported. See answer https://stackoverflow.com/a/14309108/1082541 below.

As Brent Worden already mentioned, default values are not supported.

I had issues with using Option.setType too. I always got a null pointer exception when calling getParsedOptionValue on an option with type Integer.class. Because the documentation was not really helpful I looked into the source code.

Looking at the TypeHandler class and the PatternOptionBuilder class you can see that Number.class must be used for int or Integer.

And here is a simple example:

CommandLineParser cmdLineParser = new PosixParser();

Options options = new Options();
options.addOption(OptionBuilder.withLongOpt("integer-option")
                      .withDescription("description")
                      .withType(Number.class)
                      .hasArg()
                      .withArgName("argname")
                      .create());

try {
    CommandLine cmdLine = cmdLineParser.parse(options, args);

    int value = 0; // initialize to some meaningful default value
    if (cmdLine.hasOption("integer-option")) {
        value = ((Number)cmdLine.getParsedOptionValue("integer-option")).intValue();
    }

    System.out.println(value);
} catch (ParseException e) {
    e.printStackTrace();
}

Keep in mind that value can overflow if a number is provided which does not fit into an int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...