Argument option using JCommander

Ismail Sen picture Ismail Sen · Jul 4, 2014 · Viewed 7.3k times · Source

I'm new with JCommander and I'm trying to use it in my JAVA Command Line Application.

Fisrt thing I did is I've created my CommandLineArguments class.

Now, I'm trying to print options given with arguments in command line. But I think I'm missing something.

Here is my main class :

public static void main(String[] args) {


    String[] argv={"-h","host"};
    CommandLineArguments arguments=new CommandLineArguments();
    JCommander commands= new JCommander(arguments);

    try {

        commands.parse(argv);

        System.out.println(commands.getParsedCommand());


    } catch (Exception e) {
        System.out.println(e.getMessage());
        commands.usage();
    }
}

Once I run this class, I got : null as output. Seems like getParsedCommand() is not used as it should.

Can someone tell me how to use JCOmmmander methods correctly so I can see options given with arguments?

What I'm trying to do here is, once the user runs java -jar myApp.jar -port portNumber -h hostname -d database -c collection I wanna be able to get portNumber hostname database and collection value so I can establish a connexion and send queries.

Hope I was clear enough.

Ismail

Answer

Robby Cornelissen picture Robby Cornelissen · Jul 4, 2014

You need to make a distinction between commands and parameters. In the example you give, you only need parameters.

The first chapter of the JCommander documentation provides a clear enough example of how to handle parameters. If your CommandLineArguments class is annotated as in the example, the parameter values should be correctly set in that class after calling parse(argv).

Commands are explained in a later chapter dealing with more complex command-line syntaxes.