3

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

Aleksandr Podkutin
  • 2,532
  • 1
  • 20
  • 31
Ismail Sen
  • 571
  • 2
  • 14
  • 27

1 Answers1

2

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • It's not clear in the documentation. In the given example: `Assert.assertEquals(jct.verbose.intValue(), 2);` We know that value is `2`. How do we get the value when we use a temrminal and we don't know the given value ? – Ismail Sen Jul 04 '14 at 09:16
  • 1
    I'm sorry, but I don't understand your confusion. Just calling `jct.verbose.intValue()` will give you the value. Add your `CommandLineArguments` class to the question and it might be able to give you a better answer. – Robby Cornelissen Jul 04 '14 at 09:19
  • Ok, You just answered my question. Merci – Ismail Sen Jul 04 '14 at 09:25
  • Yeah I did. Well,when youy told me : "Just calling `jct.verbose.intValue()` will give you the value" this was the answer I was looking for. – Ismail Sen Jul 04 '14 at 09:28