J-CLOPS logoTWI-JUG logo

Constraints

Often it does not make sense to allow more than one option of a given set. J-Clops allows you to indicate restrictions of this kind by annotating your context class. In the following example, a user can specify either --verbose or --quiet, but not both:

@OneOf({"quiet", "verbose"})
public class MyProgram {

    private boolean verbose;

    public void setVerbose () {
        this.verbose = true;
    }
    
    public void setQuiet () {
        this.verbose = false;
    }
    ...
}
            
The @OneOf annotation takes an array of long option names as argument and forces J-Clops to check that exactly one of these options is always present on the command line. If you want to be a little less restrictive, i.e., also allow the user to leave out the options alltogether, and make --quiet the default, you can use the @AtMostOneOf annotation instead:
@AtMostOneOf({"quiet", "verbose"})
public class MyProgram {

    private boolean verbose = false;

    public void setVerbose () {
        this.verbose = true;
    }
    
    public void setQuiet () {
        this.verbose = false;
    }
    ...
}
            
Note that the fact that --quiet is now the default results from initializing the verbose field to false and has nothing to do with J-Clops.

You can use both types of annotations together on the same class (but with different options of course). Because of limitations in the Java annotation system however, you need to do some extra work when you want to use the same type of constraint more than once:

@OneOfList( {
    @OneOf({"quiet", "verbose"}),
    @OneOf({"cr", "lf", "crlf"})
} )
@AtMostOneOfList( {
    @AtMostOneOf({"small", "medium", "big"}),
    @AtMostOneOf({"left", "centered", "right"})
} )
public class MyProgram {
    ...
}
        
which is, admittedly, a whole mouthful.