问题描述
我希望以下代码段具有互斥的命令选项:
@Command(description = "test command")
public void test(
@Option(names = { "-a"},required = true,arity = "0",description = "print A") boolean a,@Option(names = { "-b"},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"},description = "print A") boolean a ;
@Option(names = { "-b"},description = "pint B") boolean b ;
}
}
解决方法
您应该能够使用带 @ArgGroup
注释的方法,就像带 @ArgGroup
注释的字段一样。
例如:
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",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
注释的方法;它最初会被一个新实例调用,并且这个实例将在 setter 方法被调用后被修改。
(通过启用 picocli 跟踪,我们可以更深入地了解幕后发生的事情。)