【问题标题】:Picocli: can the parser be configured using annotations?Picocli:可以使用注释配置解析器吗?
【发布时间】:2019-05-23 07:55:27
【问题描述】:

我使用 PicoCLI 来解析参数。我需要为其中一个子命令指定setStopAtPositional(true)。有没有办法通过注释来做到这一点?目前我这样做:

cmd.getSubcommands().get("submit").setStopAtPositional(true);

但最好在指定提交命令的方法中指定它以将整个规范集中在一个地方。

我的班级有这样的结构:

@Command(...)
public class CommandLine implements Callable<Void> {

    @Command(...)
    public void submit( ... options) {
    }
}

【问题讨论】:

    标签: picocli


    【解决方案1】:

    Picocli 允许为每个子命令配置不同的解析器,并且您的建议适用于您的示例。

    目前没有用于配置解析器的注释 API,在未来的版本中添加它可能是一个想法。

    请注意,通过CommandLine 对象设置解析器配置将更改该命令及其子命令和子子命令的完整层次结构。

    如果您想更改单个命令的解析器配置(不影响其子命令),请使用CommandLine.getCommandSpec().parser() 获取其ParserSpec 对象并对该ParserSpec 对象进行配置(以下示例)。

    问题没有提到这一点,但可能有人担心在 picocli 3.9.x 中使用parseWithHandler 方法在配置后调用程序有点笨拙。使用 picocli 4.0 中添加的 execute 方法会变得更好。

    例如:

    @Command(subcommands = B.class)
    class A implements Callable<Integer> {
    }
    
    @Command(name = "B")
    class B implements Callable<Integer> {
    
        @Command
        public int subB(... options) {
        }
    }
    
    public static void main(String... args) {
        CommandLine cmdA = new CommandLine(new A());
    
        // Example 1: configure the B command _and_ its subcommands
        cmdA.getSubcommands().get("B").setStopAtPositional(true);
    
        // Example 2: configure the A command _only_ (not the subcommands)
        cmdA.getCommandSpec().parser().caseInsensitiveEnumValuesAllowed(true);
    
        // parse input and run the command
        int exitCode = cmdA.execute(args);
        System.exit(exitCode);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 2013-09-30
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 2019-07-26
      相关资源
      最近更新 更多