位置

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

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

通常,當命令列中定義了引數時(無論是長選項還是短選項),它們會被對映到某個選項。一般來說,有選項選項引數引數,其中後者是未對映到任何特定選項的引數。

未識別的引數可以進行二次對映邏輯,此時位置資訊很重要。透過選項位置,您實際上是在告訴命令解析器如何解釋普通的原始模糊引數。

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

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]
© . This site is unofficial and not affiliated with VMware.