Picocli:可以使用注释配置解析器吗?

Picocli: can the parser be configured using annotations?

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

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

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

我的 class 有这样的结构:

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

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

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

目前没有注释 API 来配置解析器,在未来的版本中添加它可能是个好主意。

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

如果要更改 单个 命令的解析器配置(不影响其子命令),请使用 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);
}