I was trying to obtain the following command line configuration:
myprogram.jar --op1 --other parameters OK
myprogram.jar --other parameters --op2 OK
myprogram.jar --op1 --op2 should launch ParameterException
I don't want to set --operation=[1|2] cause they are very different type of operations
Is there a way to obtain this with JCommander?
CodePudding user response:
I think what you're looking is to validate the parameters globally.
Unfortunately JCommander does not support it, with simple annotations. As found in its documentation: http://jcommander.org/#_global_parameter_validation
For this you need to write your own validator after parsing parameters, such as below example:
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
class Main {
@Parameter(names = "-op1")
private final boolean op1 = false;
@Parameter(names = "-op2")
private final boolean op2 = false;
public static void main(String[] args) {
Main main = new Main();
JCommander.newBuilder()
.addObject(main)
.build()
.parse(args);
main.run();
}
public void run() {
if (op1 && op2) {
throw new ParameterException("Choose only either op1 or op2, but not both");
}
}
}
