jjzjj

java - Apache 公共(public) CLI : how to prevent using short-name for options?

coder 2024-03-12 原文

在 Apache Commons CLI 库中,是否可以绕过短名称的使用,从而强制用户使用长名称?

通常,选项定义如下:

new Option("u", "username", true, "automatic user name")

我想禁止使用“u”。但是,如果我用 null 或空字符串替换它,就会出现异常...

为什么有这个要求?我希望我的所有选项都只采用 --optionName=optionValue 的形式,因为我的应用程序的某些部分是 Spring Boot 并且 Spring Boot 默认识别这种格式的选项。

此外,为了在开发人员和用户之间保持一致并简化文档,我发现如果我们有一种独特的方式来使用一个选项而不是 2 个选项会更好。

最佳答案

在使用最新版本的 Apache Commons Cli 1.3.1 和 DefaultParser 时,将 null 作为短名称传递对我有用(这是现在唯一未弃用的):

    Options options = new Options();

    Option option = new Option(null, "help", true, "some desc");

    options.addOption(option);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse( options, new String[] {"--help=foobar"});

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp( "ant", options );

    assertEquals(cmd.hasOption("help"), true); 
    String optionValue = cmd.getOptionValue("help"); 
    assertEquals("foobar", optionValue);

关于java - Apache 公共(public) CLI : how to prevent using short-name for options?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479185/

有关java - Apache 公共(public) CLI : how to prevent using short-name for options?的更多相关文章

随机推荐