How can I make an option accept only some specified values like in the following example:
$ java -jar Mumu.jar -a foo
OK
$ java -jar Mumu.jar -a bar
OK
$ java -jar Mumu.jar -a foobar
foobar is not a valid value for -a
A command-line option or simply option (also known as a flag or switch) modifies the operation of a command; the effect is determined by the command's program. Options follow the command name on the command line, separated by spaces.
The open source Java Command-Line Interface (CLI) allows users to manage files in BlackPearl using a simple command-line interface. It can be downloaded from the Java CLI page on GitHub.
public interface CommandLineParser. A class that implements the CommandLineParser interface can parse a String array according to the Options specified and return a CommandLine . Version: $Id: CommandLineParser.java 1443102 2013-02-06 18:12:16Z tn $
I've wanted this kind of behaviour before, and never came across a way to do this with an already provided method. That's not to say it doesn't exist. A kind of lame way, is to add the code yourself such as:
private void checkSuitableValue(CommandLine line) {
if(line.hasOption("a")) {
String value = line.getOptionValue("a");
if("foo".equals(value)) {
println("OK");
} else if("bar".equals(value)) {
println("OK");
} else {
println(value + "is not a valid value for -a");
System.exit(1);
}
}
}
Obviously there would be nicer ways to do this than the long if/else, possibly with an enum
, but that should be all you'd need. Also I've not compiled this, but I reckon it should work.
This example also does not make the "-a" switch mandatory, since that wasn't specified in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With