Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an option value always return 'null'

I have stuck with the following situation. Whenever I try to get an option value, it returns null.

Here is the code fragment:

    public static Options configureOptions() {      
    Option groupOption = Option.builder("g")
            .longOpt("group")
            .required(false)
            .desc("The group of the user.")
            .build();
    Options allOptions = new Options();
    allOptions.addOption(taskOption);

    return allOptions;
}

public static void main(String[] args) throws ParseException {

    Options options = configureOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commands = parser.parse(options, args);
    if (commands.hasOption("group")) {
        System.out.println("group: " + commands.getOptionValue("group"));
    }
}

And running with option -g staff then the output is ALWAYS null.

java -classpath rsa-1.0.0-SNAPSHOT.jar;c:\Users\user.m2\repository\commons-cli\commons-cli\1.3.1\commons-cli-1.3.1.jar Main -g staff

like image 791
user4881671 Avatar asked Jun 19 '16 17:06

user4881671


1 Answers

Using Option.Builder, you need to specify that your groupOption has an argument by using hasArg().

Option groupOption = Option.builder("g")
            .longOpt("group")
            .required(false)
            .desc("The group of the user.")
            .hasArg() // This option has an argument.
            .build();

Javadoc:

https://commons.apache.org/proper/commons-cli/javadocs/api-release/org/apache/commons/cli/Option.Builder.html#hasArg--

Usage/Examples:

https://commons.apache.org/proper/commons-cli/usage.html

like image 77
ck1 Avatar answered Sep 22 '22 03:09

ck1