cbeust / jcommander

Command line parsing framework for Java
Apache License 2.0
1.95k stars 332 forks source link

Use return type of method to determine parameter type #524

Closed thnaeff closed 11 months ago

thnaeff commented 3 years ago

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)
tgallagher2017 commented 2 years ago

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.

thnaeff commented 2 years ago

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

thnaeff commented 2 years ago

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