The Apache Commons CLI, Command Line Parsing

Quite a few times when writing a Java application, there is the need of passing command line arguments to the program itself. Usually, the application would have to validate those arguments. For example, making sure that the user passed in a numeric value, or a boolean one. Sometimes validate that the user has passed in all the mandatory parameters etc. This process is usually very tedious.

Fortunately enough, there are a few libraries that can do that for us. My preferred one is the Apache Commons CLI. It’s a great library, with an extremely straightforward to use API. It also provides multiple parser styles. Naming a few:

  • GNU like options (i.e –key ~/.ssh/key.pem)
  • POSIX like options (i.e -xvfz)
  • Short and long options (i.e -k ~/.ssh/key.pem or -key ~/.ssh/key.pem)
  • Java like property options (i.e -Dkeystore=~/.ssh/key.pem)

The library can automatically parse the arguments to their correct types (i.e Integer, String, Boolean etc), throwing appropriate exceptions when the user has passed a wrong argument type. Additionally, it validates those arguments and it ensures that all the mandatory arguments have been passed to the application. The programmer would only have to retrieve the values that the user has passed, without having to worry about anything else.

The Maven dependency is:

<dependency>
	<groupId>commons-cli</groupId>
	<artifactId>commons-cli</artifactId>
	<version>1.2</version>
</dependency>

As i mentioned above its API is simple self-explaining and straight forward. At the very least there are two things that a developer needs to create. The command line Options and a CommandLineParser.

The Options can be created like below

An example of creating the command line parser is below.

The entire example, along with some unit tests, can be found on Github.