Java: Generic method for Enums

前端 未结 1 706
日久生厌
日久生厌 2020-12-25 12:16

Help me understand generics. Say I have two enums as inner classes like so:

public class FoodConstants {
    public static enum Vegetable {
        POTATO,BR         


        
相关标签:
1条回答
  • 2020-12-25 12:53
    public static <E extends Enum<E>>
    String getEnumString(Class<E> clazz, String s){
      for(E en : EnumSet.allOf(clazz)){
        if(en.name().equalsIgnoreCase(s)){
          return en.name();
        }
      }
      return null;
    }
    

    The original has a few problems:

    1. It accepts an instance of the enum instead of the class representing the enum which your question suggests you want to use.
    2. The type parameter isn't used.
    3. It returns the input instead of the instance name. Maybe returning the instance would be more useful -- a case-insensitive version of Enum.valueOf(String).
    4. It calls a static method on an instance so you can iterate. EnumSet does all the reflective stuff for you.
    0 讨论(0)
提交回复
热议问题