JOpt Simple version 2.4.1
Examples of Usage
Training the Parser
There are two ways to tell JOpt Simple how to recognize command line
options. Each involves instantiating an OptionParser object,
and each can be used with the other.
Some examples will use the following class:
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
class Command {
private boolean flag;
private int count;
private double quantity;
private Writer output;
private boolean operateVerbosely;
private List directories = new ArrayList();
Command() {
this.output = new OutputStreamWriter( System.out );
}
void setFlag( boolean flag ) {
this.flag = flag;
}
void setCount( int count ) {
this.count = count;
}
void setQuantity( double quantity ) {
this.quantity = quantity;
}
void setOutput( Writer output ) {
if ( output != null )
this.output = output;
}
void setOperateVerbosely( boolean operateVerbosely ) {
this.operateVerbosely = operateVerbosely;
}
void setPath( List directories ) {
this.directories.addAll( directories );
}
boolean isReady() {
return output != null;
}
void execute() {
printSummary( buildSummary() );
}
private String buildSummary() {
StringBuffer buffer = new StringBuffer();
if ( operateVerbosely )
buffer.append( "The following are the settings of this command: " );
buffer.append( "flag = " ).append( flag );
buffer.append( ", count = " ).append( count );
buffer.append( ", quantity = " ).append( quantity );
buffer.append( ", path = " ).append( directories );
if ( operateVerbosely )
buffer.append( ". Thank you for your attention." );
return buffer.toString();
}
private void printSummary( String summary ) {
PrintWriter printer = null;
try {
printer = new PrintWriter( output, true );
printer.println( summary );
}
finally {
if ( printer != null )
printer.close();
}
}
}
- You can specify short options by creating an
OptionParserusing the constructor which accepts an option specification string:import joptsimple.OptionParser; import joptsimple.OptionSet; public class ShortOptionSpecificationExample { public static void main( String[] args ) { OptionParser parser = new OptionParser( "fc:q::" ); OptionSet options = parser.parse( args ); System.out.println( "got -f? " + options.has( "f" ) ); boolean gotC = options.has( "c" ); System.out.println( "got -c? " + gotC ); if ( gotC ) System.out.println( "arguments of -c: " + options.argumentsOf( "c" ) ); boolean gotQ = options.has( "q" ); System.out.println( "got -q? " + gotQ ); if ( gotQ ) System.out.println( "arguments of -q: " + options.argumentsOf( "q" ) ); } } - You can specify short or long options by calling the
acceptsmethod onOptionParser, and a chain of methods thereafter to form sentences in an internal "domain-specific language" for option parsers:import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.List; import joptsimple.OptionException; import joptsimple.OptionParser; import joptsimple.OptionSet; public class DomainSpecificLanguageExample { private static final String FLAG_OPTION = "f"; private static final String COUNT_OPTION = "c"; private static final String QUANTITY_OPTION = "q"; private static final List VERBOSE_OPTIONS = Arrays.asList( new String[] { "v", "talkative", "chatty" } ); private static final String OUTFILE_OPTION = "output-file"; private static final List PATH_OPTIONS = Arrays.asList( new String[] { "cp", "classpath" } ); private static final List HELP_OPTIONS = Arrays.asList( new String[] { "h", "?" } ); public static void main( String[] args ) throws Exception { OptionParser parser = new OptionParser() { { accepts( FLAG_OPTION, "turns on a flag" ); accepts( COUNT_OPTION ).withRequiredArg() .describedAs( "count" ).ofType( Integer.class ); accepts( QUANTITY_OPTION ).withOptionalArg() .describedAs( "quantity" ).ofType( Double.class ); acceptsAll( VERBOSE_OPTIONS, "behave more verbosely" ); accepts( OUTFILE_OPTION ).withOptionalArg() .describedAs( "file" ).ofType( File.class ); acceptsAll( HELP_OPTIONS, "shows this help message" ); acceptsAll( PATH_OPTIONS ).withRequiredArg() .describedAs( "path1" + File.pathSeparatorChar + "path2:..." ) .ofType( File.class ) .withValuesSeparatedBy( File.pathSeparatorChar ); } }; try { OptionSet options = parser.parse( args ); if ( options.has( "?" ) ) parser.printHelpOn( System.out ); else { Command command = buildCommandFrom( options ); if ( command.isReady() ) command.execute(); else System.err.println( "command not ready" ); } } catch ( OptionException ex ) { parser.printHelpOn( System.err ); System.err.println( "====" ); System.err.println( ex.getMessage() ); } } private static Command buildCommandFrom( OptionSet options ) throws Exception { Command command = new Command(); command.setFlag( options.has( FLAG_OPTION ) ); command.setOperateVerbosely( options.has( "v" ) ); if ( options.has( COUNT_OPTION ) ) command.setCount( ( (Integer) options.valueOf( COUNT_OPTION ) ).intValue() ); if ( options.hasArgument( QUANTITY_OPTION ) ) command.setQuantity( ( (Double) options.valueOf( QUANTITY_OPTION ) ).doubleValue() ); File outputFile = (File) options.valueOf( OUTFILE_OPTION ); if ( outputFile != null ) command.setOutput( new FileWriter( (File) options.valueOf( OUTFILE_OPTION ) ) ); command.setPath( options.valuesOf( "cp" ) ); return command; } }
Types of Argument Options
Without action other than accepts() and the
with*Arg methods, the domain-specific language will arrange for
arguments of options to be of type String. By using method
ofType on the result of with*Arg, you can tell
JOpt Simple to convert an option's arguments to a type of your choosing,
provided that type has either:
- a public static
valueOfmethod which takes a singleStringargument and whose return type is the type itself, or - a public constructor which takes a single
Stringparameter.
Obtaining Arguments of Options
If an option is specified to accept arguments of type String,
you can obtain its argument value via method argumentOf on
class OptionSet. argumentOf casts the result to
type String for you, with the attendant
ClassCastException if the argument values are of another type.
If you want or need to do the casting yourself, use valueOf.
For a list of an option's arguments, use argumentsOf or
valuesOf. With the plural versions of the methods, you will
need to downcast items out of the list -- so be aware of the types you
specified for the option arguments.
Generating Command Line Help
In the preceding example, we see that it
configures the parser with a "help" option which, if specified, prints a
help screen by calling the printHelpOn method of
OptionParser. Here is what the help screen looks like:
Option Description
------ -----------
-?, -h shows this help message
-c <Integer: count>
--classpath, --cp <File: path1:
path2:...>
-f turns on a flag
--output-file [File: file]
-q [Double: quantity]
-v, --chatty, --talkative behave more verbosely
Handling Exceptions
JOpt Simple's option parser raises some derivative of
OptionException if it encounters problems during parsing.
These exceptions are unchecked, so you don't have to do anything with
such an exception if you don't want to. The rationale behind this decision is
that you will most likely be invoking JOpt Simple's functionality from a
main() method or very near to it, where a failure such as
unrecognized arguments can just stop down the JVM and yield a stack trace
without much user or programmer inconvenience. So, without any exception
handling at all, as in the short options
example, a user would see something like this:
Exception in thread "main" joptsimple.UnrecognizedOptionException: 'x' is not a recognized option
at joptsimple.OptionException.unrecognizedOption(OptionException.java:63)
at joptsimple.OptionParser.validateOptionCharacters(OptionParser.java:477)
at joptsimple.OptionParser.handleShortOptionCluster(OptionParser.java:426)
at joptsimple.OptionParser.handleShortOptionToken(OptionParser.java:419)
at joptsimple.OptionParserState$2.handleArgument(OptionParserState.java:38)
at joptsimple.OptionParser.parse(OptionParser.java:391)
at ShortOptionSpecificationExample.main(ShortOptionSpecificationExample.java:7)
If you want to handle the exception yourself, you can just catch
OptionException in your code, as in the DSL
example, and do whatever you please with the contents of the exception,
perhaps using the help generation facility.
© Copyright 2004-2008 Paul R. Holser, Jr. All rights reserved.
Last modified: $Id: examples.html,v 1.20 2008/07/10 16:37:27 pholser Exp $