cbeust / jcommander

Command line parsing framework for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@-syntax not working with command objects

mkarg opened this issue · comments

It seems there is a bug in the resolution of the @-syntax when command objects are used:

public class BugDemo {

    public static void main(String[] args) {
        Builder builder = JCommander.newBuilder().addObject(new BugDemo()).verbose(1);
        JCommander jCommander = builder.build();
        jCommander.addCommand(new Cmd());
        jCommander.parse(args);
    }

    @Parameters(commandNames = "cmd")
    static class Cmd {

        @Parameter(names = "--foo")
        String foo;

        @Override
        public String toString() {
            return String.format("foo %s", this.foo);
        }
    }

}

When executed with command and options in a single line cmd --foo X, this works just fine.

But when executed with @-syntax cmd @conf.txt where conf.txt includes the sole line --foo X, this fails with a strange message:

Exception in thread "main" com.beust.jcommander.ParameterException: Was passed main parameter '--foo X' but no main parameter was defined in your arg class
	at com.beust.jcommander.JCommander.initMainParameterValue(JCommander.java:961)
	at com.beust.jcommander.JCommander.parseValues(JCommander.java:762)
	at com.beust.jcommander.JCommander.parse(JCommander.java:363)
	at com.beust.jcommander.JCommander.parseValues(JCommander.java:803)
	at com.beust.jcommander.JCommander.parse(JCommander.java:363)
	at com.beust.jcommander.JCommander.parse(JCommander.java:342)
	at de.quipsy.cli.BugDemo.main(BugDemo.java:18)

@cbeust Please find my solution proposal in PR #533. :-)