picocli - PicoCLI :我如何使用@ArgGroup 作为方法?
问题描述
我想为以下代码段提供互斥的命令选项:
@Command(description = "test command")
public void test(
@Option(names = { "-a"}, required = true, arity = "0", description = "print A") boolean a,
@Option(names = { "-b"}, required = true, description = "pint B") boolean b)
//
}
如果我将@ArgGroup 用于类字段,那么它可以工作,但我想为方法实现相同的效果。
class TestClass{
@ArgGroup(exclusive = true, multiplicity = "1")
private Sample sample = new Sample();
public static class Sample {
@Option(names = { "-a"}, required = true, arity = "0", description = "print A") boolean a ;
@Option(names = { "-b"}, required = true, description = "pint B") boolean b ;
}
}
解决方案
您应该能够使用@ArgGroup
-annotated 方法,就像@ArgGroup
-annotated 字段一样。
例如:
class SomeCommand implements Runnable {
private Sample sample;
@ArgGroup(exclusive = true, multiplicity = "1")
void setGroup(Sample sample) {
System.out.printf("setGroup was called with %s%n", sample);
this.sample = sample;
}
static class Sample {
@Option(names = "-a", required = true, arity = "0", description = "print A") boolean a ;
@Option(names = "-b", required = true, description = "print B") boolean b ;
public String toString() {
return String.format("Sample[a=%s, b=%s]@%x", a, b, hashCode());
}
}
public void run() {
System.out.printf("In run, sample=%s%n", this.sample);
}
public static void main(String... args) {
//System.setProperty("picocli.trace", "DEBUG");
new CommandLine(new SomeCommand()).execute("-a");
}
}
当我运行它时,我看到以下输出:
setGroup was called with Sample[a=false, b=false]@7de62196
In run, sample=Sample[a=true, b=false]@7de62196
因此,您可以使用@ArgGroup
-annotated 方法;它最初会被一个新实例调用,并且这个实例将在调用 setter 方法后被修改。
(通过启用 picocli 跟踪,我们可以更深入地了解幕后发生的事情。)
推荐阅读
- aix - 在 AIX 7.1 上检查文件对于给定用户是否可执行的命令
- reactjs - 获取位置的未知错误 GeolocationPositionError 代码 2 - Firefox Linux Mint
- ios - 使用 AWS Appsync 和 GraphQL 查询 Dynamo DB 中的多个表
- java - hadoop3.1.3无法运行jar文件
- reactjs - 如何使用 react-native 处理自定义字体和 fontWeight
- python - 重塑(n 行 xn 列)python 列表到 pandas DataFame
- php - 将 PEM 格式的公钥传递给 openssl_pkey_get_public 会给出错误:0906D06C:PEM 例程:PEM_read_bio:no start line
- c++ - 如何将节点存储在数组 C++ 中?
- php - @ORM\ManyToOne(试图将对象而不是 int 值填充到列中的学说)
- javascript - 如何在 Node 的 Express Router 中使用两个或多个 route.js 文件?