2

I want to have mutually exclusive command options for the below snippet :

@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) 

    // 
}

If I use @ArgGroup for a class field then It works but I want to achieve the same for methods.

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 ;
    
    }
}
Ankit
  • 99
  • 6

1 Answers1

1

You should be able to use an @ArgGroup-annotated method, just like an @ArgGroup-annotated field.

For example:

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");    
    }
}

When I run this, I see the following output:

setGroup was called with Sample[a=false, b=false]@7de62196
In run, sample=Sample[a=true, b=false]@7de62196

So, you can use an @ArgGroup-annotated method; it will initially be invoked with a new instance, and this instance will be modified after the setter method was called.

(We can get more insight into what is happening under the hood by enabling picocli tracing.)

Remko Popma
  • 35,130
  • 11
  • 92
  • 114