简短格式
简短样式的 POSIX 选项通常只是长格式的同义词。如下所示,选项 --arg
等于 -a
。
-
编程方式
-
注解
-
传统注解
CommandRegistration stringWithShortOption() {
return CommandRegistration.builder()
.command("example")
.withTarget()
.function(ctx -> {
String arg = ctx.hasMappedOption("arg") ? ctx.getOptionValue("arg") : null;
return String.format("Hi arg='%s'", arg);
})
.and()
.withOption()
.longNames("arg")
.shortNames('a')
.required()
.and()
.build();
}
@Command(command = "example")
String stringWithShortOption(
@Option(longNames = "arg", shortNames = 'a', required = true) String arg) {
return String.format("Hi '%s'", arg);
}
@ShellMethod(key = "example")
String stringWithShortOption(
@ShellOption(value = { "--arg", "-a" }) String arg) {
return String.format("Hi '%s'", arg);
}
如果类型定义为标志(意味着类型为 布尔值),则组合格式的简短选项非常强大。这样,您可以将标志的存在定义为 -abc
、-abc true
或 -abc false
。
-
编程方式
-
注解
-
传统注解
CommandRegistration multipleBooleans() {
return CommandRegistration.builder()
.command("example")
.withTarget()
.function(ctx -> {
Boolean a = ctx.hasMappedOption("a") ? ctx.getOptionValue("a") : null;
Boolean b = ctx.hasMappedOption("b") ? ctx.getOptionValue("b") : null;
Boolean c = ctx.hasMappedOption("c") ? ctx.getOptionValue("c") : null;
return String.format("Hi a='%s' b='%s' c='%s'", a, b, c);
})
.and()
.withOption()
.shortNames('a')
.type(boolean.class)
.defaultValue("false")
.and()
.withOption()
.shortNames('b')
.type(boolean.class)
.defaultValue("false")
.and()
.withOption()
.shortNames('c')
.type(boolean.class)
.defaultValue("false")
.and()
.build();
}
@Command(command = "example")
public String multipleBooleans(
@Option(shortNames = 'a') boolean a,
@Option(shortNames = 'b') boolean b,
@Option(shortNames = 'c') boolean c) {
return String.format("Hi a='%s' b='%s' c='%s'", a, b, c);
}
@ShellMethod(key = "example")
public String multipleBooleans(
@ShellOption(value = "-a") boolean a,
@ShellOption(value = "-b") boolean b,
@ShellOption(value = "-c") boolean c)
{
return String.format("Hi a='%s' b='%s' c='%s'", a, b, c);
}