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:
- Create a class holding all the options you wish to parse.
- 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)
- In your main method, create an instance of your options holder class
- 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
- 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.