简体   繁体   中英

Pass a generic enum with custom implemented methods as a parameter

I'd like to map the Label -> Value of a generic enum instance. This is feasible with this code:

  public static <T extends Enum<T>> List<Map<String, String>> mapEnumValues(T[] myEnumValues) {
    List<Map<String, String>> list = new ArrayList<>();
    for (T myEnumValue : myEnumValues) {
        Map<String, String> map = new HashMap<>();
        map.put("label", myEnumValue.name());
        map.put("value", myEnumValue.toString());
        list.add(map);
    }
    return list;
}

But now I want to use another key for the map, which is for instance a method getLabel() implemented by every one of my enums. For example, given:

  public interface Labelizable{
      public String getLabel();
  }
  
  static public enum Options implements Labelizable {
  option01("Option 01", 1), option02("Option 02", 2)
  ... constructor, getLabel(), ....

So I'd like to replace that row of code with:

map.put("label", myEnumValue.getLabel()); // instead of .name()

In order to do that I should declare something on the signature thst forces the parameter to be an enum that implements the getLabel() method. I tried, for example,

public static <T extends Enum<T implements Labelizable>> 

and some other syntax like this with no success. Is there any way to achieve this behaviour, or the fact that enums can't inherit prevent such a method?

The syntax is:

public static <T extends Enum<T> & Labelizable> 
    List<Map<String, String>> mapEnumValues(T[] myEnumValues) {

You put the superclass that your generic parameter has to inherit first, then the interfaces that it has to implement, all separated by & .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM