cbeust / jcommander

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

Use Enum::toString to print but Enum#valueOf(Enum::name) to match #550

Closed CaryCatZ closed 1 month ago

CaryCatZ commented 1 year ago

The formatter uses Enum::toString to print. But parse uses Enum::name to match. So, you might type X but it says it's invalid but also X is an allowed value in the help. This may happen when toString method was overrode.

For example: The enumeration is:

public enum Resolution {
    R_4K, // could not start with a number
    R_1080P,
    R_720P;

    @Override
    public String toString() { // for human-reading
        return this.name().substring(2)
    }
}

The help may be like this:

...
-res
Possible Values: [4K, 1080P, 720P]
...

So, the user might type -res 4K

java -jar program.jar -res 4K

But the program gave this unthinkable report: Invalid value for -res parameter. Allowed values: [4K, 1080P, 720P]

mkarg commented 4 months ago

@CaryCatZ Thank you for reporting this issue. While it is arguable whether it is a good idea to provide a user-friendly name here (see https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#toString-- which says that this is intended to be the declared name of the constant), I think this is simply a bug. So I would kindly encourage you to provide a PR containing a fix and a unit test proving its effect.

CaryCatZ commented 2 months ago

Thanks for considering this issue and the PR will be provided soon.