Iterate enum values using java generics

前端 未结 10 996
余生分开走
余生分开走 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:49

    To get the value of the generic enumeration:

      protected Set enum2set(Class> 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(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;
      }
    
    }
    

提交回复
热议问题