Login | Register
My pages Projects Community openCollabNet

optparse
Project home

There will be a brief maintenance window every Friday at 17:00 Pacific.
For further details, see CollabNet's maintenance and upgrade policy.

If you were registered and logged in, you could join this project.

Summary A simple command line option parser in Java.
Category libraries
License CollabNet/Tigris.org Apache-style license
Owner(s) chap

Abstract

The optparse liibrary provides a very simple and straightforward API for basic command line option parsing. It is kept as simple as possible to ensure instant usage without unnecessary (because rather standard) configuration stuff.

This obviously is possible because some assumptions are made that should fit almost all regular usage scenarios but might not fit your special one.

The most important limitation is that option parsing is limited to POSIX and GNU style options, e.g. -o (POSIX style) or --output (GNU style). Any other style besides that e.g. /? (MS Windows style) or -help (X Toolkit style) is not supported (and cannot be configured).

Well, why use this?

Yes, we all know -- there are already more than enough option parsing solutions around. But none of these kept it as simple as this one.

Example

Just a silly example to sketch what this is all about. This example parses all kinds of supported option styles. Apart from that it features my personally preferred configuration style (a fluent interface).

public static void main ( String[] args ) {

OptionParser optionParser = new OptionParser()
.register( new OptionalFlag( "flag", 'f' ) )
.register( new MandatoryParameter( "type", 't' ) )
.register( new OptionalParameter( "values" ) );
optionParser.parse( args );
// optional: throw Exception if mandatory options are not defined
optionParser.assertMandatoryOptions();
// optional: throw Exception if parameters have no value
optionParser.assertMandatoryOptionValues();
// optional: throw Exception if unknown options ocurred
optionParser.assertUnregisteredOptions();

// getOption will only return null if the option was not registered
System.out.println( "Flag: " +
optionParser.getOption( "flag" ).isAvailable() ? "true" : "false";
System.out.println( "Type: " + optionParser.getOption( "type" ).getValue() );
Option valuesOption = optionParser.getOption( "values" );
System.out.println( "Input: " + valuesOption.isAvailable() ? valuesOption.getValues().toString : "not provided";

}

Please do not bother me because of the missing exception handling or any other totally great code tweaks. This is just an example.