更新:picocli 4.3已发布,改进了对参数组中位置参数的支持。
@Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
public class Grades implements Runnable {
static class StudentGrade {
@Parameters(index = "0") String name;
@Parameters(index = "1") BigDecimal grade;
}
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<StudentGrade> gradeList;
@Override
public void run() {
gradeList.forEach(e -> System.out.println(e.name + ": " + e.grade));
}
public static void main(String[] args) {
System.exit(new CommandLine(new Grades()).execute(args));
}
}
使用此输入运行上述程序:
Alice 3.5 Betty 4.0 "X Æ A-12" 3.5 Zaphod 3.4
产生以下输出:
Alice: 3.5
Betty: 4.0
X Æ A-12: 3.5
Zaphod: 3.4
在 picocli 4.3 之前,应用程序可以执行以下操作来完成此操作:
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Command(name = "grades", mixinStandardHelpOptions = true, version = "grades 1.0")
public class Grades implements Runnable {
@Parameters(arity = "2",
description = "Each pair must have a name and a grade.",
paramLabel = "(NAME GRADE)...", hideParamSyntax = true)
List<String> gradeList;
@Override
public void run() {
System.out.println(gradeList);
Map<String, BigDecimal> map = new LinkedHashMap<>();
for (int i = 0; i < gradeList.size(); i += 2) {
map.put(gradeList.get(i), new BigDecimal(gradeList.get(i + 1)));
}
}
public static void main(String[] args) {
int exitCode = new CommandLine(new Grades()).execute(args);
System.exit(exitCode);
}
}