-
Notifications
You must be signed in to change notification settings - Fork 5
OptionsParser
The OptionsParser
(see source) works a bit like getopt()
in C, but it uses Java annotations to specify command line options in a manner that is natural to Java. Typically you'll write something like
List<String> arguments=Lists.newArrayList("-optionA","valueA","-flagB","positional1","positional2");
OptionsParser parser = new OptionsParser("");
MyOptions options = (MyOptions) parser.parser(arguments);
The options are defined by a class which implements the HasOptions
interface and uses the @Options
and @Positional
annotations, i.e.
package com.ontology2.centipede.parser;
import java.util.List;
public class InheritedOptionExample implements HasOptions {
@Option(name="johnny",defaultValue="1234",description="one hundred feet")
public Long john;
@Option(description="the count",defaultValue="1")
public long count;
@Option(description="a garden variety list")
public List<Integer> numbers;
@Positional
public List<String> positional;
}
Note that you can use String
, any primitive type, or the class version of any primitive type for the type of any option. You can also specify List<T>
where T
is any type supported by the system. If you specify a List, the system will maintain a list of parameters. Right now the system will split parameters on commas and also allow you to specify multiple list parameters:
-numbers 2,4,6,8 -john 55 -numbers 10
will populate numbers
with [2,4,6,8,10]
.
At this time, OptionsParser
only supports "long" parameters, you cannot write
-R11
but you have to write
-R 11
Boolean parameters are treated as flags that default to false
and are true if the flag is set. In the case of a boolean parameter we do not consume the next token, but in the case of any other parameter we do consume the next token.
Moving left to right, once we encounter the first token that isn't part of an option, all further parameters are treated as positional parameters that will be written into a List
that is marked by the @Positional
. Any further tokens that start with a dash will be treated as positional parameters and not parsed by the OptionsParser
By specifying a class for the contextualConverter
field of the @Option
attribute, you can specify a class that converts the string token to the type of the field. The contextualConverter
also gets a copy of the options object so it can use other options to contextualize the value. For example, this can be used to implement something like a 'current working directory' for a Hadoop application that takes a large number of input paths. See this example in the source code.