Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java commons-cli, options with list of possible values

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
like image 212
Alexandru Avatar asked Nov 27 '09 23:11

Alexandru


People also ask

What is CLI option?

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.

What is CLI in Java?

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.

What is command line parser Java?

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 $


1 Answers

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.

like image 194
Grundlefleck Avatar answered Sep 30 '22 18:09

Grundlefleck