Check these out:
- http://commons.apache.org/cli/
- http://www.martiansoftware.com/jsap/
Or roll your own:
- http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
For instance, this is how you use commons-cli to parse 2 string arguments:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;//not a good practice, it serves it purpose
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
}
String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");
System.out.println(inputFilePath);
System.out.println(outputFilePath);
}
}
usage from command line:
$> java -jar target/my-utility.jar -i asd
Missing required option: o
usage: utility-name
-i,--input <arg> input file path
-o,--output <arg> output file
Answer from Vinko Vrsalovic on Stack OverflowCheck these out:
- http://commons.apache.org/cli/
- http://www.martiansoftware.com/jsap/
Or roll your own:
- http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
For instance, this is how you use commons-cli to parse 2 string arguments:
import org.apache.commons.cli.*;
public class Main {
public static void main(String[] args) throws Exception {
Options options = new Options();
Option input = new Option("i", "input", true, "input file path");
input.setRequired(true);
options.addOption(input);
Option output = new Option("o", "output", true, "output file");
output.setRequired(true);
options.addOption(output);
CommandLineParser parser = new DefaultParser();
HelpFormatter formatter = new HelpFormatter();
CommandLine cmd = null;//not a good practice, it serves it purpose
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
System.out.println(e.getMessage());
formatter.printHelp("utility-name", options);
System.exit(1);
}
String inputFilePath = cmd.getOptionValue("input");
String outputFilePath = cmd.getOptionValue("output");
System.out.println(inputFilePath);
System.out.println(outputFilePath);
}
}
usage from command line:
$> java -jar target/my-utility.jar -i asd
Missing required option: o
usage: utility-name
-i,--input <arg> input file path
-o,--output <arg> output file
Take a look at the more recent JCommander.
I created it. I’m happy to receive questions or feature requests.
Parse cmd line arguments to your java utilities with Args4J
gratis - Command-line option parser for Java - Software Recommendations Stack Exchange
How to manually parse command line arguments?
Is there a static method to get command-line arguments?
Videos
I discovered Args4J a few weeks ago, but just today sat down to add a feature to a flat file parsing and format verification utility that I am writing for work ( referenced here ).
The author, Kohsuke Kawaguchi, is the lead developer of my namesake, Jenkins-ci.
For once, the tutorial and howto for a package is concise, and leaves out all sorts of other dependencies that mainly serve to trip up someone attempting to learn the new thing.
If you write utility programs that need command line argument's parsed, consider checking out Args4J.
You could check out FeSimpleArgs
I believe it fulfills all your requirements:
Concept: A very light-weight command-line parser. Takes arguments in either a String or String[] form, returns a class instance holding the arguments in a map, and the parameters in a list.
Requirements:
- Takes an arbitrary String or String[] (i.e. doesn't use the arguments from the command line) Yes
- Takes arguments in a similar format to getopt (the GNU enhanced version); specifically:
- Multiple single-letter options can be joined (e.g. -a -b -c to -abc) Yes
- Supports long options (e.g. --message="Hello!") (though it doesn't have to support single-dash long options) Yes
- Assumes all non-option-like bits at the end are parameters to be passed normally (e.g. -abc --long="Hello!" param1 param2 tells me that the parameters are param1 and param2) Yes
- -- can be used to separate options from arguments (e.g. -ab --custom="hello" -- -file_starting_with_hyphen -another gives me the options/flags a, b, and custom with the appropriate values, and tells me that the arguments are -file_starting_with_hyphen and -another) Yes
- Whitespace can be part of arguments, if it's quoted. Yes
An option name followed by a value is parsed as the option having that value (e.g. -h foo says that there is an option, h, with a value, foo) Yes
Entirely cross-platform Yes
- Doesn't need me to specify which options I'm looking for (i.e. I pass it a String or String[] and it tells me which flags/options were set, as opposed to it looking for the options I want to set and assuming the rest are arguments) Yes
as to usage:
- Free (as in beer) Yes - Apache 2.0
- Can be legally used in any project (i.e. not noncommercial, not GPL) Yes - Apache 2.0
- Minimal copyright license (Not copyleft -- I like not worrying about legal issues, and I hate people trying to tell me that I can't use my work, however, I damned well, please) Yes - Apache 2.0
Published under Apache 2.0 license.
Ideal, but not necessary:
- Small -- one file Yes (one file for the parser, one for the unit tests, not needed to parse)
- Uses the built-in interfaces (java.util.Map, specifically) to return data. (This is so I can write my own function more easily later) **Sort of ** (Returns a class holding a java.util.Map of arguments and a List of parameters)
USAGE Usage: 1) Construct an instance of FeSimpleArgs
FeSimpleArgs parser = new FeSimpleArgs();
2) Use it to parse your arguments:
FeSimpleArgs.Result result = parser.parse ("-def=value1 --GHI=value2 -a -b -c=value3 -n=\"foo bar baz\" -- param1 -param2");
3) Examine your results: From the above, result will consist of a Map containing the following arguments and flags (note that there's no real meaning to "argument" or "flag", I'm just using those terms to separate whether they take values or not - all are in the same Map).
- a
- b
- d
- e
- f with value=value1
- GHI with value=value2
- c with value=value3
- n with value=foo bar baz (note quotes are stripped)
And a list containing these parameters (note that the leading hyphen is preserved) - param1 - -param2
4) Profit?
For other examples, please see the included unit tests.
Disclaimer: I am the author of FeSimpleArgs
picocli may be of interest. It is a single source file to encourage command line app authors to include it as source as a simpler alternative to shading jars into an uberjar. It also fulfills all other requirements stated in the OP - UPDATE: except for the requirement that options cannot be fixed at compile time :-(.
UPDATE 2: picocli 3.x offers a programmatic API in addition to the annotations API, so now it meets all requirements. Note that Groovy CliBuilder is based on picocli since Groovy 2.5. This is exactly what the OP is asking for: dynamically add options and positional parameters to a command.
It recently added autocompletion functionality.
Another feature you may like is its colorized usage help.

Parser features:
- Annotation API: parsing is one line of code in your application
- Programmatic API: everything that is possible with annotations can be done programmatically
- Strongly typed everything - command line options as well as positional parameters
- POSIX clustered short options (
<command> -xvfInputFileas well as<command> -x -v -f InputFile) and GNU long options - An arity model that allows a minimum, maximum and variable number of parameters, e.g,
"1..*","3..5" - Subcommands (can be nested to arbitrary depth)
- Works with Java 5 and higher
The usage help message is easy to customize with annotations (without programming). For example:
(source)
I couldn't resist adding one more screenshot to show what usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

Disclaimer: I created picocli. Feedback or questions very welcome.
Is there a static method somewhere that gets command-line arguments? In Go there is os.Args to get command-line arguments, rather than just as arguments to the main method. It is much more elegant, and as a result, I'm wondering if there is a Java equivalent in the form of a static method or static field.
EDIT: To everyone asking how is it more elegant - Imagine you're working on a hobby project, you realized after a week of development that you probably should use command-line arguments to get a value. Now you have to route a String[] called args through 12 different classes and methods. In what world is that anywhere as elegant as a static method?