3

I am using argparse4j to parse command line arguments. I want to add an argument that when present, sets a boolean to true, otherwise it defaults to false. I don't want to include the true or false in the argument, just the identifier, so it would look something like this when run:

java firstArg --enable-boolean

This answer shows that in Python, I could set the action of the argument to store a true or false value like so:

parser.add_argument('-b', action='store_true', default=False)

How can I do the same thing in Java, using argparse4j?

Community
  • 1
  • 1
yellavon
  • 2,821
  • 12
  • 52
  • 66
  • This is also referred to as a command-line "flag." It helps if you show more code; what you have already got working, which part is not working. I added in example code from the answer you linked, since you want to know how to do the same thing. – Air Mar 06 '15 at 23:33

1 Answers1

5

You're looking for the Arguments.storeTrue() action:

Arguments.storeTrue() and Arguments.storeFalse() are special cases of Arguments.storeConst() using for storing values true and false respectively. In addition, they create default values of false and true respectively. For example:

public static void main(String[] args) throws ArgumentParserException {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("prog");
    parser.addArgument("--foo").action(Arguments.storeTrue());
    parser.addArgument("--bar").action(Arguments.storeFalse());
    parser.addArgument("--baz").action(Arguments.storeFalse());
    System.out.println(parser.parseArgs(args));
}
$ java Demo --foo --bar
Namespace(baz=true, foo=true, bar=false)
Air
  • 8,274
  • 2
  • 53
  • 88