Arity
Arity defines how many parameters option parsing takes.
There are limitations in a legacy annotation compared to annotation
and programmatic use of arity settings. These are mentioned in notes in
below samples.
|
-
Programmatic
-
Annotation
-
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);
}
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 doesn’t support defining minimum arity.
|
-
Programmatic
-
Annotation
-
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);
}
In below example we have option arg1 and it’s defined as type String[]. Arity defines that it needs at least 1 parameter and not more that 2. As seen in below spesific exceptions TooManyArgumentsOptionException and NotEnoughArgumentsOptionException are thrown to indicate arity mismatch.
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.