0

我想为以下代码段提供互斥的命令选项:

@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 ;
    
    }
}
4

1 回答 1

1

您应该能够使用@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 跟踪,我们可以更深入地了解幕后发生的事情。)

于 2021-01-14T06:51:41.463 回答