【问题标题】:PicoCLI : How can I use @ArgGroup for a method?PicoCLI :我如何使用@ArgGroup 作为方法?
【发布时间】:2021-04-18 09:20:16
【问题描述】:

我想为下面的 sn-p 提供互斥的命令选项:

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

【问题讨论】:

    标签: picocli


    【解决方案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-12-13
      • 2020-09-09
      • 1970-01-01
      • 2023-03-24
      • 2021-04-29
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多