J-CLOPS logoTWI-JUG logo

Asking for help

We end this tutorial by showing you how to implement a --help option which displays an automatically generated 'usage message'. In our example, the Program class will be used as the option context. It contains a method execute which does whatever the program is supposed to do after all command line options are parsed. We also provide a method runMain, discussed below, which can be called in the applications main method. With this setup, parsing the command line options and running the program has become very simple:

  public static void main (String[] args) {
        new Program().runMain(args);
  }
            
In fact, the code given below is a very good starting point for an abstract class which may serve as a super class for all your options contexts, with execute as an abstract method to be overridden every time. (Note that J-Clops annotations are indeed inherited.)

The --help option method simply sets a boolean flag:

public class Program {

    private boolean helpWanted = false;

    @Option(shortName = 'h', 
            description = "Displays this message", 
            exclude = Exclusion.OTHER_OPTIONS_OR_ARGUMENTS)
    public void setHelp() {
        this.helpWanted = true;
    }
    ...
}
            
(The exclude line in the @Option annotation ensures that no other command line arguments are allowed when --help is present.)

The helpWanted flag is checked as part of the runMain method:

    public void runMain(String[] args) {
        CLManager manager = new CLManager(this);
        try {
            manager.parse(args);
            if (helpWanted) {
                System.err.println(manager.getUsageMessage());
            } else {
                execute();
            }
        } catch (CLParseException ex) {
            System.err.println(ex);
            System.err.println(manager.getUsageMessage());
        }
    }
            
and that is all there is to it.