1

在 Picocli 中,是否可以配对任意长度的参数?例如:

grades Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0

其中每一对必须有一个名字和一个等级,但总长度是未知的,即:

grades <name> <grade> [<name> <grade>]*

参数图是最接近的,可能会起作用,例如

@Parameters(index = "0..*") Map<String, float> grades;

会解析:

grades Abby=4.0 Billy=3.5 Caily=3.5 Danny=4.0

进入地图,但如果不存在平等会更好......

4

1 回答 1

1

更新: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);
    }
}
于 2020-05-05T05:38:16.087 回答