Home > Java, Uncategorized > Args4j library for parsing Java command line arguments

Args4j library for parsing Java command line arguments

args4j is a great tool for parsing command line arguments in Java.

Here’s the description from its homepage:

  • It makes the command line parsing very easy by using annotations.
  • You can generate the usage screen very easily.
  • You can generate HTML/XML that lists all options for your documentation.
  • Fully supports localization.
  • It is designed to parse javac like options (as opposed to GNU-style where ls -lR is considered to have two options l and R.)
  • It is licensed under the MIT license.

It is fairly simple to use:

  1. Create a class holding all the options you wish to parse.
  2. Annotate the fields of the class, telling args4j information about the command line arguments (what flags are necessary, what are the various short and long ways of specifying that argument)
  3. In your main method, create an instance of your options holder class
  4. Pass the instance from step 3 into an instance of CmdLineParser class, and then call parseArgument on the array of strings passed into the main method
  5. If no parse exceptions are thrown, your options object has all of the required options fields filled in, which can then be queried via normal getters.

The sample main class provided by the args4j folks is especially useful; in this example they do not create a separate class to hold the options, but that is certainly an option.

I’m really not sure how this stacks up to other command line parsing tools for Java; suffice to say it’s small, fast, the annotations make it a breeze to specify a set of names for different named arguments… it just works.  Please use this instead of trying to roll your own options parsing code.

  1. Absolute fan
    September 14, 2011 at 11:48 am

    If like me you were looking for documentation on dev.java.net, you’d better visit the new project’s homepage: http://args4j.kohsuke.org/

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: