cbeust / jcommander

Command line parsing framework for Java
Apache License 2.0
1.96k stars 334 forks source link

Custom enum formatter for help. #482

Open mimic2300 opened 4 years ago

mimic2300 commented 4 years ago

Hi, please make it possible to customize the default enum values in the help. Type names are not always sufficient.

Example of how I modified it. You can use it or think of another way. Create custom DefaultUsageFormatter with overridden method appendAllParametersDetails(..) and under line where is if (type.isEnum()) {

modify this: String valueList = EnumSet.allOf((Class<? extends Enum>) type).toString();

on this:

Collection valueList;
if (IEnumFormatter.class.isAssignableFrom(type)) {
  Object[] items = EnumSet.allOf((Class<? extends Enum>) type).toArray();
  if (items.length > 0) {
    valueList = ((IEnumFormatter) items[0]).getValues();
  } else {
    valueList = Collections.emptyList();
  }
} else {
  valueList = EnumSet.allOf((Class<? extends Enum>) type);
}

Create a new interface:

public interface IEnumFormatter {
  List<String> getValues();
}

Usage on custom (my) enum is:

public enum ActionType implements IEnumFormatter {

  KILL("kill"),
  SACRIFICE_HAMSTER("sacrifice");

  private final String alias;

  ActionType(String alias) {
    this.alias = alias;
  }

  @Override
  public List<String> getValues() {
    var values = values();
    var list = new ArrayList<String>(values.length);
    for (var v : values) {
      list.add(v.alias);
    }
    return list;
  }
}

PS: Method newLineAndIndent(..) in DefaultUsageFormatter must be protected not private.

Thanks and let me know ;-)