How can I eliminate duplicated Enum code?

后端 未结 15 899
眼角桃花
眼角桃花 2020-12-24 13:40

I have a large number of Enums that implement this interface:

/**
 * Interface for an enumeration, each element of which can be uniquely identified by its co         


        
15条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 13:55

    Here I have another solution:

    interface EnumTypeIF {
    String getValue();
    
    EnumTypeIF fromValue(final String theValue);
    
    EnumTypeIF[] getValues();
    
    class FromValue {
      private FromValue() {
      }
    
      public static EnumTypeIF valueOf(final String theValue, EnumTypeIF theEnumClass) {
    
        for (EnumTypeIF c : theEnumClass.getValues()) {
          if (c.getValue().equals(theValue)) {
            return c;
          }
        }
        throw new IllegalArgumentException(theValue);
      }
    }
    

    The trick is that the inner class can be used to hold "global methods".

    Worked pretty fine for me. OK, you have to implement 3 Methods, but those methods, are just delegators.

提交回复
热议问题