public class OptionParser extends Object
OptionParser
class provides facilities to parse
command line options.
public static void main(String[] args) { // options v and O may be clumped, as in "-vO" BooleanOption v = new BooleanOption("v"); // verbose BooleanOption O = new BooleanOption("O"); // optimize BooleanOption nowarn = new BooleanOption("nowarn"); // don't warn StringOption classpath = new StringOption("classpath"); // explicit classpath StringClumpOption logfile = new StringClumpOption("logfile="); // logfile try { OptionParser parser = new OptionParser(new CmdLineOption[]{opt1, opt2, opt3, opt4, opt5}); int nIndexAfterOptions = parser.parse(args); if (v.value) System.out.println("Verbose set"); else System.out.println("Verbose not set"); if (O.value) System.out.println("Optimize"); else System.out.println("Don't optimize"); if (nowarn.value) System.out.println("Don't warn"); else System.out.println("Warn"); if (null == classpath.value) System.out.println("Classpath not set"); else System.out.println("Classpath: " + classpath.value); if (null == logfile.value) System.out.println("No logfile specified"); else System.out.println("Logfile: " + logfile.value); System.out.println("First non-option argument: " + Integer.toString(nIndexAfterOptions)); } catch (BadCommandLineException e) { System.out.println("usage()\n" + e); } catch (InvalidOptionException e) { System.out.println("bad options specified: " + e); } }
BooleanOption
,
StringOption
,
StringClumpOption
Constructor and Description |
---|
OptionParser(CmdLineOption[] options)
Creates a new command line option parser based on the given options.
|
Modifier and Type | Method and Description |
---|---|
int |
parse(String[] args)
Parses a command line for options, looking for longest match first.
|
public OptionParser(CmdLineOption[] options) throws InvalidOptionException
options
- the array of options.InvalidOptionException
- if two options have the same key or one key equals "-".public int parse(String[] args) throws BadCommandLineException
args
- the command line arguments to parse.BadCommandLineException
- if there is an illegal option on the command line.Copyright © 2023. All rights reserved.