You are here: Home Hacking options - java lib for parsing command line options
options - java lib for parsing command line options

options - java lib for parsing command line options

Java 1.5 introduces annotations and generics. Using these, options allows you to handle command line option parsing with very little effort.

Introduction

A simple example:

public class SimpleExample {
 @Option(shortName="n",
documentation="Name of the instance to create.")
 public String name;

public static void main(String[] args) {
 SimpleExample me = new SimpleExample();
    OptionParser<SimpleExample> parser =
new OptionParser<SimpleExample>(me);
    try {
    parser.parse(args);
    } catch (OptionParseException e) {
      System.out.println(e.getMessage());
      System.out.println(parser.usage());
      System.exit(1);
    }
    System.out.println("Name: " + me.name);
  }
}

The point of this, apart from being compact, is that it does not intrude on the structure of your classes: no sub-classing, no interfaces to implement.

Currently, OptionParser understands Boolean, Long, String, File and URL. It also understands Collection<Boolean>, et cetera, for options that can occur multiple times (e.g. "-vvvvv" -> me.verbose.size() == 5).

Handling arguments (e.g. file names) is straightforward; your instance simply implements the handleArgument(String) method and will then be called with each file name as it occurs.

public boolean handleArgument(String arg) {
File f = new File(arg);
if (!f.exists())
throw new RuntimeException("File does not exist.");
return true;
}

Returning false will stop options parsing and the remainder will be returned from parser.parse().

There is also a CommandOptionParser that helps you create collective (or meta) commands like svn (i.e. "svn help", "svn update", et.c.).

Complete examples can be found in the examples directory in the source distribution.

Feedback

Please feedback to options at quest windwards net.

License

options is released under GNU Lesser General Public License, version 3. 

Source

The project is hosted at Bitbucket. Go to the public options repository

.

Releases

Download options version 0.9.3 jar file.

Or, if you are a follower of maven2, you would endow your pom.xml thus:
<project>
...
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.windwards</groupId>
<artifactId>options</artifactId>
<version>0.9.3</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>

... and add a repository entry in settings.xml pointing to http://windwards.net/repository/.

Version history

v0.9.3 (2011-02-28)

  • Support java.io.File and java.net.URL options.

v0.9.2 (2010-06-24)

  • Fixed the other dependency on Java 1.6 :/.
  • Now support integer arguments (not just long).

v0.9.1(2009-10-06)

  • Fixed the dependency on Java 1.6. Can now be run by 1.5 too.

v0.9 (2009-02-27)

  • Initial release.
Document Actions