Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute the parsed command with jcommander?

I'm using JCommander to interact with the user on the command line.

The JCommander setup looks like the following:

JCommander jCommander = new JCommander();
jCommander.addCommand(new Command1());
jCommander.addCommand(new Command2());
jCommander.addCommand(new Command3());

Scanner scanner = new Scanner(System.in);
jCommander.usage();
jCommander.parse(splitAsArgs(scanner.nextLine())));

Now I can use getParsedCommand() to retrieve the name of the command being parsed.

My problem is that it seems very difficult to translate the returned String to the actual object that was passed to addCommand. I could hold a map externally, that does this kind of translation, but that is redundant since all this is already known by jcommander.

How shall I translate from the name of the parsed command back to command object itself?

Usually all my commands I pass to jcommander implement Runnable or something similiar. So if jcommander would allow me to access the object that was parsed, it would make my life much easier.

like image 211
SpaceTrucker Avatar asked Dec 26 '22 02:12

SpaceTrucker


1 Answers

The solution is the following:

String parsedCommand = jCommander.getParsedCommand();
JCommander parsedJCommander = jCommander.getCommands().get(parsedCommand);
Object commandObject = parsedJCommander.getObjects().get(0);

The parsedJCommander object has only a single command object, which in my case is the Runnable I would like to execute.

like image 158
SpaceTrucker Avatar answered Jan 06 '23 08:01

SpaceTrucker