跳到主要内容

变元数

ChatGPT-4o-mini 中英对照 Arity

Arity 定义了选项解析接受多少个参数。

备注

annotationprogrammatic 使用的 arity 设置相比,legacy annotation 存在一些限制。这些限制在下面的示例中以注释形式提及。

CommandRegistration zeroOrOne() {
return CommandRegistration.builder()
.command("example")
.withOption()
.longNames("arg")
.arity(OptionArity.ZERO_OR_ONE)
.and()
.build();
}
java

表 1. 选项的元数

最小/最大
ZERO0 / 0
ZERO_OR_ONE0 / 1
EXACTLY_ONE1 / 1
ZERO_OR_MORE0 / 整数最大值
ONE_OR_MORE1 / 整数最大值
备注

legacy annotation 不支持定义最小参数个数。

CommandRegistration zeroOrOneWithMinMax() {
return CommandRegistration.builder()
.command("example")
.withOption()
.longNames("arg")
.arity(0, 1)
.and()
.build();
}
java

在下面的示例中,我们有选项 arg1,它被定义为类型 String[]。参数个数定义为至少需要 1 个参数,最多不超过 2 个。如下面特定的异常所示,抛出了 TooManyArgumentsOptionExceptionNotEnoughArgumentsOptionException 来指示参数个数不匹配。

shell:>e2e reg arity-errors --arg1
Not enough arguments --arg1 requires at least 1.

shell:>e2e reg arity-errors --arg1 one
Hello [one]

shell:>e2e reg arity-errors --arg1 one two
Hello [one, two]

shell:>e2e reg arity-errors --arg1 one two three
Too many arguments --arg1 requires at most 2.
bash