Java Command-Line Interfaces (Part 8): Argparse4j
Taking some inspiration from Python's argparse module, Argparse4j is a useful command-line argument parser library to consider when working with Python scripts.
Join the DZone community and get the full member experience.
Join For FreeArgparse4j is a "Java command-line argument parser library" that its main page describes as "a command line argument parser library for Java based on Python's argparse module." In this post, I will look briefly at using Argparse4j 0.7.0 to process command-line arguments similar to those parsed in the seven earlier posts in this series on command-line processing in Java.
The arguments "definition" stage of command-line processing with Argparse4j can be accomplished via the ArgumentParser interface and its addArgument(String...) method. The return type of the addArgument(String...)
method is an instance of the Argument interface. Implementations of that interface (usually ArgumentImpl) provide methods for setting the characteristics of each argument. Because each of these methods returns an instance of Argument
, these calls can be chained together in a highly fluent manner.
"Definition" Stage With Argparse4j
final ArgumentParser argumentParser =
ArgumentParsers.newArgumentParser("Main", true);
argumentParser.addArgument("-f", "--file")
.dest("file")
.required(true)
.help("Path and name of file");
argumentParser.addArgument("-v", "--verbose")
.dest("verbose")
.type(Boolean.class)
.nargs("?")
.setConst(true)
.help("Enable verbose output.");
In the above code listing, an instance of ArgumentParser
is instantiated with a static initialization method that expects a String
argument representing the script or program name that will be included in usage/help output. The second argument to the ArgumentParsers's newArgumentParse(String, boolean) method specifies that "help" options -h
and --help
will automatically be supported.
The first argument defined in the above code listing allows for a file path and name to be specified on the command line. The strings "-f" and "--file" are passed to the addArgument(String...)
method, meaning that either -f
or --file
can be used on the command line to specify the file path and name. Three additional methods [dest(String), required(boolean), and help(String)] are called on the instances of Argument
created as part of the specification of this first argument. These three methods respectively specify a name by which the argument can be referenced in the code, that the argument must be present on the command line, and the string to be displayed when help is requested for that argument.
The second argument defined in the above code listing passes the strings "-v" and "--verbose" to the addArgument(String...)
method to allow this argument to be represented on the command line with either the short or long option name. Like the first argument, this one has the name it will be referenced by in the code set by the dest(String)
method and has its string for "help" output specified with the help(String)
method. This second argument is not required and so the required(boolean)
method is unnecessary here.
The second argument's definition has a few additional methods on Argument
called. I used type(Class<T>) to demonstrate the ability to explicitly specify the Java data type expected for the argument. I also needed to specify the combination of the nargs(String) and setConst(Object) methods to specify that the verbosity argument does not need a value provided with the flag. This allows me to specify -v
or --verbose
with no "true" or "false" after those options expected to be explicitly stated.
The "parsing" stage of command-line processing is supported in argparse4j with a call to the ArgumentParser's parseArgs(String[]) method. The next code listing demonstrates this.
"Parsing" Command Line Arguments With Argparse4j
final Namespace response = argumentParser.parseArgs(arguments);
Parsing requires only a single statement and returns an instance of Namespace.
The "interrogation" stage of command line processing with Argparse4j involves accessing the parsed command-line arguments from the Map
that the Namespace
instance wraps. The keys of this map are the strings specified with the dest(String)
method and the values of the map are the values associated with those argument names. Interrogating these values is demonstrated in the next code listing.
"Interrogating" Command Line Arguments With Argparse4j
final String filePathAndName = response.getString("file");
final Boolean verbositySet = response.getBoolean("verbose");
out.println(
"Path/name of file is '" + filePathAndName
+ "' and verbosity is "
+ (Boolean.TRUE.equals(verbositySet) ? "SET" : "NOT SET")
+ ".");
In the just listed code, the keys of "file" and "verbose" were used because those same strings were provided with the dest(String)
method when defining the expected arguments.
The full source code from which the code snippets above were extracted can be seen on GitHub.
The next screen snapshot demonstrates running the simple Java application without any arguments and the message that is displayed regarding the missing required "file" argument.
The all uppercase "FILE" shown in the above screen snapshot comes from the string that was specified in the dest(String)
method when defining the expected argument. In other words, that dest(String)
specification set both the string by which the argument mapping is keyed internally and the target string displayed in the help/usage.
The next screen snapshot demonstrates several variations of typical uses of the "file" and "verbose" options.
The final screen snapshot demonstrates that help information that is provided for -h
or --help
options because the original instance of ArgumentParser
was created with the "addHelp" argument set to true
.
Here are some additional characteristics of Argparse4j to consider when selecting a framework or library to help with command-line parsing in Java.
- Argparse4j is open source and licensed with the MIT License.
- The argparse4j-0.7.0.jar (December 2015) is approximately 89 KB in size and has no additional third-party library dependencies.
- Argparse4j does not make use of annotations.
- The online documentation includes a Clojure example.
- I suspect that Java developers who write their scripts in Python (particularly if they use argparse) would experience advantages when using argparse4j in their Java applications that need to parse command-line arguments.
- (I find Apache Commons CLI to be intuitive when processing command-line arguments in Java because I much more frequently parse command line arguments in Groovy than in Java and Groovy supplies built-in Apache Commons CLI support)
- Argparse4j inspired the development of argparse4s for Scala.
Argparse4j is just one of many Java-based command line processing libraries. The characteristic of Argparse4j that most sets it apart from the numerous other options is its argparse heritage. Given that, I believe that the Java developers most likely to select Argparse4j for their Java command line processing needs would be those developers who frequently parse command line arguments in Python-based scripts and tools using argparse or who prefer command parsing semantics of Python and argparse.
Additional References
- Argparse4j
- Argparse4j User Manual
- Argparse4j Examples
- Argparse4j API Documentation (Javadoc)
- Argparse4j Source on GitHub
- Argparse4j Releases (Downloads)
- Argparse4j 0.7.0 (Maven)
Published at DZone with permission of Dustin Marx, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments