Annotations
Of course not all real world examples are as simple as the 'Hello world' example of
the previous pages.
Sometimes it is necessary to add some extra configuration information for your options.
We have chosen not to use separate configuration files for this purpose, but have instead opted
for using annotations in the option context class. Annotation syntax can sometimes be
a bit verbose, but annotations have the advantage of being a direct
part of the application source
and need little extra housekeeping.
As a first example, assume you would like the --times
option of the
'Hello world!' application also to be known as a short option -t
,
then you must add an @Option
annotation to the setter method
in the option context class, as follows:
import be.ugent.twijug.jclops.annotations.Option;
...
@Option(shortName='t')
public void setTimes(int times) {
this.times = times;
}
(Do not forget to also import the annotation class.)
The @Option
annotation also has a longName
attribute
which allows use to override the long option name which was automatically derived
from the method name. If you prefer --times-to-repeat
,
then you write
@Option(shortName='t',longName="times-to-repeat")
public void setTimes(int times) {
this.times = times;
}
although in this particular case the same result could have been obtained by renaming the setter
to
setTimesToRepeat
(note how
CamelCase is converted to
dash-separated-words).
The @Option
annotation can also be used with a method whose name does not begin
with set
and would therefore not automatically be recognised as an option
setter.
@Option(shortName='t',longName="times-to-repeat")
public void initializeRepeatCount(int times) {
this.times = times;
}
(In this case, a
longName
attribute is obligatory.)
Conversely, you can annotate a setter method with @NotAnOption
if you do not want it to be recognised as an option.
@NotAnOption
public void setBorder(Border border) {
...
}
However, in most cases this indicates that you should be thinking of refactoring
your option context class. Option context and application context need not
necessarily be represented by the same object.