Iterate enum values using java generics

前端 未结 10 953
余生分开走
余生分开走 2020-12-02 10:55

I\'m trying to find a way to iterate through an enum\'s values while using generics. Not sure how to do this or if it is possible.

The following code illustrates

相关标签:
10条回答
  • 2020-12-02 11:39

    Here below an example of a wrapper class around an Enum. Is a little bit weird bu is what i need :

    public class W2UIEnum<T extends Enum<T> & Resumable> {
    
    public String id;
    public String caption;
    
    public W2UIEnum(ApplicationContext appContext, T t) {
        this.id = t.getResume();
        this.caption = I18N.singleInstance.getI18nString(t.name(), "enum_"
                + t.getClass().getSimpleName().substring(0, 1).toLowerCase()
                + t.getClass().getSimpleName().substring(1,
                        t.getClass().getSimpleName().length()), appContext
                .getLocale());
    }
    
    public static <T extends Enum<T> & Resumable> List<W2UIEnum<T>> values(
            ApplicationContext appContext, Class<T> enumType) {
        List<W2UIEnum<T>> statusList = new ArrayList<W2UIEnum<T>>();
        for (T status : enumType.getEnumConstants()) {
            statusList.add(new W2UIEnum(appContext, status));
        }
        return statusList;
    }
    

    }

    0 讨论(0)
  • 2020-12-02 11:39

    I did it like this

        protected List<String> enumToList(Class<? extends Enum<?>> e) {
                Enum<?>[] enums = e.getEnumConstants();
                return Arrays.asList(enums).stream()
                       .map(name -> name.toString())
                       .collect(Collectors.toList());
            }
    
    0 讨论(0)
  • 2020-12-02 11:48

    Another option is to use EnumSet:

    class PrintEnumConsants {
    
        static <E extends Enum <E>> void foo(Class<E> elemType) {
            for (E e : java.util.EnumSet.allOf(elemType)) {
                System.out.println(e);
            }
        }
    
        enum Color{RED,YELLOW,BLUE};
        public static void main(String[] args) {
            foo(Color.class);
        } 
    
    }
    
    0 讨论(0)
  • 2020-12-02 11:49

    To get the value of the generic enumeration:

      protected Set<String> enum2set(Class<? extends Enum<?>> e) {
        Enum<?>[] enums = e.getEnumConstants();
        String[] names = new String[enums.length];
        for (int i = 0; i < enums.length; i++) {
          names[i] = enums[i].toString();
        }
        return new HashSet<String>(Arrays.asList(names));
      }
    

    Note in the above method the call to the toString() method.

    And then define the enumeration with such a toString() method.

    public enum MyNameEnum {
    
      MR("John"), MRS("Anna");
    
      private String name;
    
      private MyNameEnum(String name) {
        this.name = name;
      }
    
      public String toString() {
        return this.name;
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题