如何用jargo忽略额外的参数?

时间:2018-04-06 00:54:25

标签: java command-line type-safety jargo

我试图让jargo忽略任何数量的" junk-be-here"字符串。我怎样才能做到这一点?这是我提出的代码:

@Test
public void testUsage() throws Exception
{
    Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
    ParsedArguments parsedArguments = CommandLineParser.withArguments(nrOfPotatoes).parse("-n", "123", "junk-be-here");
    int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
    System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
}

但我明白了:

se.softhouse.jargo.ArgumentExceptions$UnexpectedArgumentException: Unexpected argument: junk-be-here, previous argument: 123
at se.softhouse.jargo.ArgumentExceptions.forUnexpectedArgument(ArgumentExceptions.java:299)
at se.softhouse.jargo.CommandLineParserInstance.getDefinitionForCurrentArgument(CommandLineParserInstance.java:329)
at se.softhouse.jargo.CommandLineParserInstance.parseArguments(CommandLineParserInstance.java:262)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:234)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:228)
at se.softhouse.jargo.CommandLineParser.parse(CommandLineParser.java:224)
at

.....

1 个答案:

答案 0 :(得分:0)

您可以使用indexed参数(通过不为参数指定名称),并设置variableArity(允许任意数量的参数)。

    @Test
public void testUsage() throws Exception
{
    Argument<List<String>> junk = Arguments.stringArgument().variableArity().build();
    Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
    ParsedArguments parsedArguments = CommandLineParser.withArguments(junk, nrOfPotatoes).parse("-n", "123", "junk-be-here");
    int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
    System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
    System.out.println("Junk:" + parsedArguments.get(junk));
}

打印:

Hold on, planting 123 potatoes
Junk:[junk-be-here]