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

标签 java command-line-arguments

我正在使用 argparse4j解析命令行参数。我想添加一个参数,当存在时,将 boolean 值设置为 true,否则默认为 false。我不想在参数中包含 true 或 false,只包含标识符,因此运行时它看起来像这样:

java firstArg --enable-boolean

This answer显示在 Python 中,我可以设置参数的 action 来存储 true 或 false 值,如下所示:

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

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

最佳答案

您正在寻找 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)

关于java - 使用 Argparse4j 的命令行参数设置标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28813481/

相关文章:

bash - ffmpeg 对文件夹中的每个 mp4 文件应用命令

java - Drools Spring 与 Jasper Report 导致 CompilationResult 冲突

java - 用于 http 连接的最佳 java 库?

Java 加密设置失败并出现 InvalidKeySpecException

java - 如何将java中的值类型字节数组分配给按钮

Java : Accepting command line arguments for array of objects

java - 通过 ant 构建脚本将命令行参数传递给 Java