Reputation: 5287
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 ?
Upvotes: 1
Views: 1675
Reputation: 328
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:
args
is made of the single "-c"
value;line.getArgs()
returns an empty array;line.getOptions()
returns an single entry array consisting of the expected Option
object.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...
Upvotes: 1