While passing arguments in Java through CLI we generally pass like
java -cp jar classname \"args[0]\" \"args[1]\"
I want to
In 2019, there are better libraries for building CLI applications than Apache Commons CLI.
Consider using picocli to get an ultra-compact program that automatically has colored help and optionally has command line autocompletion.
Your program could look like this:
@Command(name = "myapp", description = "Does cool stuff.", mixinStandardHelpOptions = true)
class MyApp implements Callable {
@Option(names = {"-s", "--host"}, required = true, description = "host name")
String hostname;
@Option(names = {"-u", "--user"}, required = true, description = "user name")
String username;
@Option(names = {"-p", "--password"}, interactive = true, description = "pass phrase")
char[] password;
public Integer call() {
// business logic here...
System.out.printf("host=%s, user=%s%n", hostname, username);
return 0; // exit code signalling normal termination
}
public static void main(String[] args) {
// in 1 line, parse the args, handle errors,
// handle requests for help/version info, call the business logic
// and obtain an exit status code:
int exitCode = new CommandLine(new MyApp()).execute(args);
System.exit(exitCode);
}
}
Some advantages of using picocli:
Callable
or Runnable
, you can set up and execute your program in one line of code in the main
method. The business logic goes in the call
(or run
) method.mixinStandardHelpOptions = true
means that --help
and --version
options are added automatically. These work as expected without requiring further coding.char[]
array so it can be nulled out from memory when the work is done - these are good security practices.See Autocomplete for Java Command Line Applications for adding TAB autocompletion to this program.
Disclaimer: I maintain picocli.