簡短格式
簡短樣式 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);
}