Arity

Arity 定义选项解析所采用的参数数量。

annotationprogrammatic 使用 arity 设置相比,legacy annotation 中存在局限性。这些在以下示例的注释中提到。

  • Programmatic

  • Annotation

  • Legacy Annotation

link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]
link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]
link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]
Table 1. OptionArity
Value min/max

ZERO

0 / 0

ZERO_OR_ONE

0 / 1

EXACTLY_ONE

1 / 1

ZERO_OR_MORE

0 / Integer MAX

ONE_OR_MORE

1 / Integer MAX

legacy annotation 不支持定义最小 arity。

  • Programmatic

  • Annotation

  • Legacy Annotation

link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]
link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]
link:../../../../src/test/java/org/springframework/shell/docs/OptionSnippets.java[role=include]

在下面的示例中,我们有选项 arg1,并且将其定义为类型 String[]。Arity 定义它至少需要 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.