Core classes of the Args4J command line parser.

What is Args4J

Args4J is a command line parser. As such a parser its job is to parse the String-array passed to the main() method and transfer the values to a java object, which includes type conversion. The entry point into this parsing is the CmdLineParser class with its parse() Method.

Args4J must know the mapping between the flag from the command line and the target for the value. There are multiple ways for Args4J:

depending on what you want, you have to do a configuration step before starting the parsing.

Examples

java Main -text newText

The standard use case is having a bean class and providing the annotations. This feature is available since the first Args4J release:

public class Bean {
    (a)Option(name="-text")
    String text;
}
public class Main {
    public static void main(String[] args) throws CmdLineException {
        Object bean = new Bean();
        CmdLineParser parser = new CmdLineParser(bean);
        parser.parse(args);
    }
}

An easy way for initializing fields and not touching the bean source code is using the FieldParser. The FieldParser scans all fields of the bean class (including inheritance) and makes them public available as options with a '-' prefix in the name. This feature is available since Args4J release 2.0.16:

public class Bean {
    String text;
}
public class Main {
    public static void main(String[] args) throws CmdLineException {
        Object bean = new Bean();
        CmdLineParser parser = new CmdLineParser(null);
        new FieldParser().parse(parser, bean);
        parser.parse(args);
    }
}

While the FieldParser is easier to use, the XmlParser supports more features. That said it supports all features which are available via annotations: usage text, specifying handlers and more. You have to provide an XML InputSource or an URL to the XML file. This feature is available since Args4J release 2.0.16:

public class Bean {
    String text;
}
public class Main {
    public static void main(String[] args) throws CmdLineException {
        Object bean = new Bean();
        CmdLineParser parser = new CmdLineParser(null);
        new XmlParser().parse(getClass().getResource(bean.getClass().getName() + ".xml"), parser, bean);
        parser.parse(args);
    }
}
<args>
  <option field="text" name="-text" usage="Output text"/>
</args>