JCommander 1.0 – Annotation driven command line parser for Java

JCommander is a small framework for easy command line parameter parsing.
You create a class that will hold all the command line arguments and annotate the fields to define which parameter will be bound to the variable.

Here is a small example from the project page:

import com.beust.jcommander.Parameter;

public class JCommanderTest {
  public List<string> parameters = Lists.newArrayList();

  @Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")
  public Integer verbose = 1;

  @Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
  public String groups;

  @Parameter(names = "-debug", description = "Debug mode")
  public boolean debug = false;

JCommanderTest jct = new JCommanderTest();
String[] argv = { "-log", "2", "-groups", "unit", "a", "b", "c" };
new JCommander(jct, argv);

Assert.assertEquals(jct.verbose.intValue(), 2);

JCommander can generate a usage description which will output something like this:

    -port           The port number
    -debug          Debug mode
    -src, --sources The source directory
    -testclass      List of classes

The project is open source (Apache 2 licence).

Similar projects are JewelCli and args4j.

Short URL for this post: https://blog.oio.de/F94JE
This entry was posted in Build, config and deploy, Java Basics and tagged , , . Bookmark the permalink.