使用 Argparse4j 的命令行参数设置标志

Setting a flag using a command-line argument with Argparse4j

我正在使用 argparse4j 来解析命令行参数。我想添加一个参数,当存在时,将布尔值设置为 true,否则默认为 false。我不想在参数中包含 true 或 false,只是标识符,所以当 运行:

时它看起来像这样
java firstArg --enable-boolean

This answer 表明在 Python 中,我可以设置参数的 action 来存储真值或假值,如下所示:

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

如何使用 argparse4j 在 Java 中做同样的事情?

您正在查找 Arguments.storeTrue() 操作:

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)