Search code examples
javaenumscode-reuse

java reuse code in enum


I had an enum like below:

public enum EOrderStatus  {

DELETE(0, "aaaa"),
CANCEL(1, "bbb"),
APPEND(2, "cccc");

private EOrderStatus(int value, String description)
{
    Description = description;
    Value = value;
}

//region common

public String getDescription() {
    return Description;
}
protected void setDescription(String description) {
    Description = description;
}
// 此枚举的描述,此值可以用于日志显示,或接口返回说明等
private String  Description;
public int getValue() {
    return Value;
}
protected void setValue(int value) {
    Value = value;
}
// int 值
private  int Value;

//endregion
}

and I have more than 100 enums like this. how can I reuse the code between region and endregion? ............................................................


Solution

  • Not sure if it is good practice, but I'd say you can't really factor out the variables, but you could save yourself repeating the methods if you are willing to use reflection.

    Given these Enums:

    enum Enum1 {
      DELETE(10, "aaaa1"),
      CANCEL(11, "bbb1"),
      APPEND(12, "cccc1");
    
      public final String description;
      public final int value;
    
      private Enum1(int value, String description) {
        this.description = description;
        this.value = value;
      }
    }
    
    enum Enum2  {
      DELETE(20, "aaaa2"),
      CANCEL(21, "bbb2"),
      APPEND(22, "cccc2");
    
      public final String description;
      public final int value;
    
      private Enum2(int value, String description) {
        this.description = description;
        this.value = value;
      }
    }
    

    You can create an utils class which reads the values using reflection:

    class EnumUtils {
    
      public static String getDescription(Class enumClass, String enumName) {
        return (String) getFieldValue(enumClass, enumName, "description");
      }
    
      public static int getValue(Class enumClass, String enumName) {
        return (Integer) getFieldValue(enumClass, enumName, "value");
      }
    
      public static Object getFieldValue(Class enumClass, String enumName, String fieldName) {
        Object value = null;
        Enum e = Enum.valueOf(enumClass, enumName);
        try {
          Field descriptionField = e.getClass().getDeclaredField(fieldName);
          value = descriptionField.get(e);
        } catch(NoSuchFieldException | IllegalAccessException ex) { /* Handle that as you want */ }
        return value;
      }
    }
    

    Then you can use it this way:

    public static void main(String[] args)  {
    
      System.out.println(EnumUtils.getDescription(Enum1.class, "DELETE"));
      System.out.println(EnumUtils.getDescription(Enum2.class, "DELETE"));
    
      System.out.println(EnumUtils.getValue(Enum1.class, "CANCEL"));
      System.out.println(EnumUtils.getValue(Enum2.class, "APPEND"));
    
    }
    

    It outputs

    aaaa1
    aaaa2
    11
    22