Mutually exclusive options using the Apache Commons CLI

I can create 2 mutually exclusive parameters using the following:

Option a = OptionBuilder.create("a"); Option b = OptionBuilder.create("b"); OptionGroup optgrp = new OptionGroup(); optgrp .setRequired(true); optgrp .addOption(a); optgrp .addOption(b); 

The above will force the user to provide either option a or option b.

But if I have a third option, c:

 Option c = OptionBuilder.create("c"); 

You can create mutually exclusive options, for example:

Or:

  • Option a must be provided OR
  • Both options b and c must be provided.

I could not see a way to do this with OptionGroup?

+6
source share
1 answer

As a workaround, I implemented the following, not ideal, but ...

 public static void validate(final CommandLine cmdLine) { final boolean aSupplied = cmdLine.hasOption(A); final boolean bAndCSupplied = cmdLine.hasOption(B) && cmdLine.hasOption(C); final boolean bOrCSupplied = !bAndCSupplied && (cmdLine.hasOption(B) || cmdLine.hasOption(C)); if ((aSupplied && bAndCSupplied) || (!aSupplied && !bAndCSupplied) || (aSupplied && bOrCSupplied )) { throw new Exception(...); } } 
+4
source

Source: https://habr.com/ru/post/980659/


All Articles