jcommander
jcommander copied to clipboard
Use return type of method to determine parameter type
Shouldn't the return type of the method be used to determine the parameter type? I ran into this issue when experimenting with enums (generic enums to be precise...) and when I tried to annotate methods with @Parameter
instead of class fields. Using the first parameter of a method call does not make sense to me unless I am missing something. The annotation should be on getters anyways without any method parameters.
Parameters on methods instead of class fields does not seem to be something that is documented, but by the @Parameter
annotation with @Target({ FIELD, METHOD })
and from various bug reports and PR's I learned that it is possible.
Test code:
public class TestCmd {
@Parameter()
public String getInputFormat() {
return "";
}
}
TestCmd cmd = new TestCmd();
JCommander jc = JCommander.newBuilder().addObject(cmd).build();
jc.usage();
throws a
java.lang.ArrayIndexOutOfBoundsException: 0
at com.beust.jcommander.Parameterized.getType(Parameterized.java:149)
at com.beust.jcommander.ParameterDescription.init(ParameterDescription.java:131)
I think the @Parameter goes on the setter() because JCommander is expecting to set the field from the command line args, not get the value.
Ha... good point @tgallagher2017 . Not sure what I was thinking at that time. I will have to try that out.
Changed the purpose of this pull request and documented the feature instead with an example.
Feature is already tested in src/test/java/com/beust/jcommander/args/Args1Setter.java