In my previous post, I looked at parsing command-line arguments in Java applications using Apache Commons CLI. In this post, I look at doing the same using a different library: args4j.

args4j takes a different approach to specifying which command-line arguments the Java application should expect than that used by Commons CLI. While Commons CLI expects objects representing the options to be individually and explicitly instantiated, args4j uses custom annotations to facilitate this "definition" stage of command-line arguments processing. Command-line options are expected to be instance-level fields on the class and are annotated with the @org.kohsuke.args4j.Option annotation. The characteristics of each command-line argument are included as attributes of this @Option annotation.

The simple application demonstrated in this post is similar to that used in my previous post and focuses on an optional and valueless -v option for specifying verbosity and a required -f option which expects a value that represents the file path and name. The next code listing demonstrates use of args4j's @Option annotation to set up these command-line arguments as annotations on class data members.

args4j definition of command-line arguments via @Option annotations:

@Option(name="-v", aliases="--verbose", usage="Print verbose status.") private boolean verbose; @Option(name="-f", aliases="--file", usage="Fully qualified path and name of file.", required=true) private String fileName;





As the above code listing demonstrates, it is easy to specify the name of the options, their usage, and whether they are required or not (default is optional). The presence of the private modifier above makes it obvious that these are attributes defined at a class level. Because there is no static modifier, we see that these are instance variables that have been annotated.

To parse the command-line options, one simply needs to instantiate a CmdLineParser and pass the command-line arguments to its parseArguments(String...) method:

Parsing command-line arguments in args4j:

final CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(arguments); } catch (CmdLineException clEx) { out.println("ERROR: Unable to parse command-line options: " + clEx); }





In the first line of Java code just shown, this is the reference to the instance of the class in which the member variables shown above are defined and annotated with the @Option annotation. In this case, I used this because the same class that defines those options is the one calling this parsing method. To do this in the same class, I needed to have an instance (non- static ) method called doMain defined in the class and invoked by the class's main function (this is shown in the complete code listing toward the end of this post). The command-line arguments as received from the class's main(final String[]) function are the array of Strings passed to the parseArguments(String[]) method.

The next two screen snapshots demonstrate application of the described code based on args4j to parsing the command-line arguments. The first image shows combinations of the short and long options for the two options. The second image shows the automatic reporting of the case where a required command-line argument was not provided.

An important feature of a command line parsing library is the ability to display usage or help information. The next code listing demonstrates an example of doing this with args4j's CmdLineParser.printUsage(OutputStream) method.

Printing usage information with args4j:

final CmdLineParser parser = new CmdLineParser(this); if (arguments.length < 1) { parser.printUsage(out); System.exit(-1); }





The usage information printed out by default by args4j is depicted in the next screen snapshot.

This post has demonstrated using arg4j to achieve some of the most common functionality related to command-line parsing in Java applications including option "definition," command-line arguments "parsing," "interrogation" of the parsed command-line arguments, and help/usage details related to the command-line arguments. The full code listing for the class partially represented above in code listings is shown now.

Full code listing for args4j demonstration Main.java :

package examples.dustin.commandline.args4j; import static java.lang.System.out; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import java.io.IOException; /** * Demonstrate args4j. */ public class Main { @Option(name="-v", aliases="--verbose", usage="Print verbose status.") private boolean verbose; @Option(name="-f", aliases="--file", usage="Fully qualified path and name of file.", required=true) private String fileName; private void doMain(final String[] arguments) throws IOException { final CmdLineParser parser = new CmdLineParser(this); if (arguments.length < 1) { parser.printUsage(out); System.exit(-1); } try { parser.parseArgument(arguments); } catch (CmdLineException clEx) { out.println("ERROR: Unable to parse command-line options: " + clEx); } out.println("The file '" + fileName + "' was provided and verbosity is set to '" + verbose + "'."); } /** * Executable function demonstrating Args4j command-line processing. * * @param arguments Command-line arguments to be processed with Args4j. */ public static void main(final String[] arguments) { final Main instance = new Main(); try { instance.doMain(arguments); } catch (IOException ioEx) { out.println("ERROR: I/O Exception encountered: " + ioEx); } } }





Here are some additional characteristics of args4j to consider when selecting a framework or library to help with command-line parsing in Java.

args4j is open source and licensed with the MIT License.

Current version of args4j (2.33) requires J2SE 5.

args4j does not require any third-party libraries to be downloaded or referenced separately.

The args4j 2.33 main JAR ( args4j-2.33.jar ) is approximately 152 KB in size.

) is approximately 152 KB in size. The Maven Repository shows 376 dependencies on args4j including OpenJDK's JMH Core and Jenkins (not surprising given Kohsuke Kawaguchi's involvement in both).

args4j has been around for a while; its 2.0.3 release was in January 2006 and it's been around in some form since at least 2003.

args4j allows a command-line parameter to be excluded from the usage output via "hidden" on the @Option annotation.

annotation. args4j allows for relationships between command-line arguments to be specified and enforced. This includes the ability to specify when two arguments cannot be supplied at the same time ("forbids") and when the presence of an argument only makes sense when another argument is also provided ("depends").

args4j supports use of enum-typed class attributes for cases where a finite set of values is applicable to the option. The @Option documentation describes how to do this under the "Enum Switch" section.

args4j provides extensibility and customizability of command-line arguments parsing via its OptionHandler class.

The args4j library is easy to use and allows for highly readable code. Perhaps the biggest consideration when deciding whether to use args4j is deciding how comfortable one is with using annotations for specifying the command-line parameters' definitions.

Additional References