Introduction to JCommander — Java command line argument parser

Parsing command line arguments is a common task, lets see how we can use JCommander to get it done nice and tidy.

Eldad Uzman
2 min readMar 15, 2022
Photo by Jonas Jacobsson on Unsplash.

Parsing command line naively

Lets take a look at typical java main method:

I’m using maven, so my POM file is:

My pom includes the maven assembly plugin with reference to the public static main method, this will create a self contained jar file with all dependencies that I can run with java runtime.

Now lets install it with mvn clean install

And run the jar file java -jar target\demo-1.0-SNAPSHOT-jar-with-dependencies.jar

Hello World!

Cool.

Now lets break it down

look at the signature of the main method:

public static void main(String[] args)

It receives a list of strings, this is a place to pass command line arguments.

Lets take on of the arguments and print it:

Lets install again:

mvn clean install

And run with a single argument java -jar target\demo-1.0-SNAPSHOT-jar-with-dependencies.jar argument1

Hello World!
The value of arg1 is: argument1

Works is not enough

With a single command line argument it seems easy, but when you have many different arguments of different types it becomes cumbersome.

There’s a better way!

Introducing jcommander

Jcommander is Java library for commandline argument.

It parses and validates the arguments passed to the program into an object which makes the use of arguments clean and neat.

Step1 — include in pom.xml

Looking at JCommander maven repository properties we can take the latest version:

<!-- https://mvnrepository.com/artifact/com.beust/jcommander -->
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>1.82</version>
</dependency>

Step2 — create a class for the arguments object:

Notice that all parameters are annotated with the parameter annotation from the jcommander package.

Step3 — use jcommanders parser to parse the args into the Args class

Install:

mvn clean install

Run with -help input:

java -jar target\demo-1.0-SNAPSHOT-jar-with-dependencies.jar -help

Usage: <main class> [options]
Options:
-debug
Debug mode
Default: false
-help
-name
name of instance
-log, -verbose
Level of verbosity
Default: 1

Now lets run with real inputs:

java -jar target\demo-1.0-SNAPSHOT-jar-with-dependencies.jar -name Eldad -verbose 2 -debug

Output:

Hello World!
The value of name is: Eldad
The value of verbose is: 2
The value of debug is: true

Nice!

--

--

Eldad Uzman
Eldad Uzman

Written by Eldad Uzman

Automation and RPA developer, python developer.

No responses yet