javacommand-lineapache-commons-cli

Commons CLI empty Options in CommandLine


I don't understand how to apply Options to DefaultParser in Commons CLI.

When CommandLine object is created, assigned Options is always empty.

Bellow block of code is how i interpreted Commons CLI docs:

public static void main(String[] args)  {

    Options options = new Options();

    options.addOption("c", false, "why are you hidding from me");

    CommandLineParser parser = new  DefaultParser();

    System.out.println(args[0]); // this prints -c

    try {

        CommandLine line = parser.parse(options, args);

        System.out.println(line.getArgs()[0]); // prints -c

        Option[] o = line.getOptions(); // this is empty for some reason

        System.out.println(o.length); // prints 0

        if (line.hasOption("c")) { // false

            System.out.println(" flag c found");
        }
    }

    catch(ParseException e ) {
        e.printStackTrace();
    }

How come that line.getOptions() is empty, and how to apply the options properly ?


Solution

  • I just tried to reproduce your issue but everything was OK for me. I created a simple maven project with only the commons-cli:commons-cli:1.3.1 dependency and a Test main class with the exact same method you provided in your question.

    When I compile and run the main method from the Windows command line, e.g. with:

    java -cp .;[path_to_commons_cli_jar]/commons-cli-1.3.1.jar Test -c
    

    then it gave me the expected output:

    Maybe there are some remaining spaces that aren't stripped in the command line you use when you launch your program within eclipse? Otherwise, your code should work fine...