元數

元數定義了選項解析需要多少個引數。

與使用annotationprogrammatic的元數設定相比,legacy annotation存在侷限性。這些在下面的示例中的註釋中提到。
  • 程式化

  • 註解

  • 舊式註解

CommandRegistration zeroOrOne() {
	return CommandRegistration.builder()
		.command("example")
		.withOption()
			.longNames("arg")
			.arity(OptionArity.ZERO_OR_ONE)
			.and()
		.build();
}
@Command(command = "example")
String zeroOrOne(
	@Option(arity = OptionArity.ZERO_OR_ONE) String arg)
{
	return String.format("Hi '%s'", arg);
}
@ShellMethod(key = "example")
String zeroOrOne(
	@ShellOption(arity = 1) String arg)
{
	return String.format("Hi '%s'", arg);
}
表 1. OptionArity
最小值/最大值

ZERO

0 / 0

ZERO_OR_ONE

0 / 1

EXACTLY_ONE

1 / 1

ZERO_OR_MORE

0 / 整數最大值

ONE_OR_MORE

1 / 整數最大值

legacy annotation不支援定義最小元數。
  • 程式化

  • 註解

  • 舊式註解

CommandRegistration zeroOrOneWithMinMax() {
	return CommandRegistration.builder()
		.command("example")
		.withOption()
			.longNames("arg")
			.arity(0, 1)
			.and()
		.build();
}
@Command(command = "example")
String zeroOrOneWithMinMax(
	@Option(arityMin = 0, arityMax = 1) String arg)
{
	return String.format("Hi '%s'", arg);
}
@ShellMethod(key = "example")
String zeroOrOneWithMinMax(
	@ShellOption(arity = 1) String arg)
{
	return String.format("Hi '%s'", arg);
}

在下面的示例中,我們有選項*arg1*,它被定義為*String[]*型別。元數定義了它至少需要 1 個引數,最多需要 2 個引數。如下面的特定異常所示,會丟擲*TooManyArgumentsOptionException*和*NotEnoughArgumentsOptionException*來指示元數不匹配。

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.