Chapter 11. StringParsers

All String-to-Object conversions are handled by StringParsers. The type of Object you want to read from the command line determines which StringParser you should use with your Option. If you need an int, use IntegerStringParser. If you need an InetAddress, use InetAddressStringParser. JSAP comes with quite a few - see the com.martiansoftware.jsap.stringparsers package.

String parsers should be accessed using the factory method getParser() of the corresponding class: for most classes, the instance returned is a singleton. In that case, the parser is also available as a constant in JSAP: for instance, the simplest way to get a parser for integers is JSAP.INTEGER_PARSER, but you can also use IntegerStringParser.getParser(). Calling the factory method is necessary if your parser has parameters (see, e.g., ForNameStringParser).

Of course, you may want to read your own object types from the command line, or at least read a type that JSAP doesn't support out of the box. No problem—just extend com.martiansoftware.jsap.StringParser. The only method you have to implement is:

public abstract Object parse(String arg) throws com.martiansoftware.jsap.ParseException;

You can now use your own StringParser with any JSAP option. JSAP won't have a built-in accessor method for the class of the object you're returning, so you'll have to use JSAPResult.getObject() or JSAPResult.getObjectArray() and re-cast the result to make use of it.