jcommander icon indicating copy to clipboard operation
jcommander copied to clipboard

Use return type of method to determine parameter type

Open thnaeff opened this issue 3 years ago • 3 comments

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)

thnaeff avatar Aug 23 '21 19:08 thnaeff

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.

tgallagher2017 avatar Jan 07 '22 06:01 tgallagher2017

Ha... good point @tgallagher2017 . Not sure what I was thinking at that time. I will have to try that out.

thnaeff avatar Jan 10 '22 01:01 thnaeff

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

thnaeff avatar Jan 30 '22 16:01 thnaeff