位置引數

位置資訊主要與命令目標方法相關

CommandRegistration.builder()
	.withOption()
		.longNames("arg1")
		.position(0)
		.and()
	.build();
使用位置引數時請謹慎,很快就會讓人混淆它們對映到哪個選項。

通常,當引數在命令列中定義時(無論是長選項還是短選項),它們會對映到一個選項。通常來說,有選項(options)選項引數(option arguments)引數(arguments),其中後者是那些沒有對映到任何特定選項的引數。

未識別的引數可以有一個次要對映邏輯,其中位置資訊很重要。透過選項位置,您實際上是在告訴命令解析如何解釋原始的、不明確的普通引數。

讓我們看看當我們不定義位置時會發生什麼。

CommandRegistration.builder()
	.command("arity-strings-1")
	.withOption()
		.longNames("arg1")
		.required()
		.type(String[].class)
		.arity(0, 2)
		.and()
	.withTarget()
		.function(ctx -> {
			String[] arg1 = ctx.getOptionValue("arg1");
			return "Hello " + Arrays.asList(arg1);
		})
		.and()
	.build();

選項 arg1 是必需的,並且沒有關於如何處理引數 one 的資訊,導致缺少選項的錯誤。

shell:>arity-strings-1 one
Missing mandatory option --arg1.

現在讓我們定義位置 0

CommandRegistration.builder()
	.command("arity-strings-2")
	.withOption()
		.longNames("arg1")
		.required()
		.type(String[].class)
		.arity(0, 2)
		.position(0)
		.and()
	.withTarget()
		.function(ctx -> {
			String[] arg1 = ctx.getOptionValue("arg1");
			return "Hello " + Arrays.asList(arg1);
		})
		.and()
	.build();

引數會被處理,直到我們得到最多 2 個引數。

shell:>arity-strings-2 one
Hello [one]

shell:>arity-strings-2 one two
Hello [one, two]

shell:>arity-strings-2 one two three
Hello [one, two]