J-CLOPS logoTWI-JUG logo

Hello world, step by step

Import the necessary classes.

import be.ugent.twijug.jclops.CLManager;
            
The J-Clops library consists of two packages: be.ugent.twijug.jclops which contains the command line manager class CLManager, and a subpackage be.ugent.twijug.jclops.annotation with annotation classes which we do not need for this simple example.

Create an option context.

public static void main(String[] args) {
    HelloWorld myProgram = new HelloWorld();
    ...
}
            
The term option context refers to an object which the command line manager needs to work with. The option context can be any type of 'plain old Java object' (POJO). There isn't any OptionContext interface, or similar, which this object must satisfy. In this and other simple examples we choose to represent the application itself as an object, and use that object as the option context. (As opposed to the application being a class full of static methods...)

Create a manager and register the option context with it.

public static void main(String[] args) {
    ...
    CLManager clm = new CLManager (myProgram);
    ...
}
            
At this point the manager will use reflection on the option context class (HelloWorld in our case) to determine what command line options are available. By default all setter methods correspond to options. Hence, because the class HelloWorld defines the following setter method:
public void setTimes(int times) {
    this.times = times;
}
            
the program automatically supports the corresponding option --times. Because the method has an integer parameter, the option should be followed on the command line by an integer.

Parse the command line.

public static void main(String[] args) {
    ...
    clm.parse(args);
    ...
}
            
The method parse of CLManager will not only parse the command line and check for syntax errors, it will also invoke the various setter methods that correspond to the options given, with the appropriate arguments. In other words, after the call to parse the option context will reflect the options and option parameters given on the command line.

Run the program.

public static void main(String[] args) {
    ...
    myProgram.run ();
}
            
The purpose of the command line manager is to change the state of the option context according to the actual command line arguments. Presumably, after parsing the command line the application should also do something. In our case we simply invoke run on the option context (which is at the same time the application object).