Passing argument in java through CLI

前端 未结 4 1807
说谎
说谎 2021-01-23 01:16

While passing arguments in Java through CLI we generally pass like

java -cp jar classname \"args[0]\" \"args[1]\"

I want to

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 01:56

    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:

    • The command name, options and option parameters use ANSI colors and styles for contrast with the other text. This doesn’t just look good, it also reduces the cognitive load on the user, making your app more user-friendly.
    • By implementing 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.
    • The mixinStandardHelpOptions = true means that --help and --version options are added automatically. These work as expected without requiring further coding.
    • You get some nice security benefits for free: this program will prompt the user for their password, and users can type in their password without it being echoed to the console. Also, the password is captured in a 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.

提交回复
热议问题