1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| package msdev.test.util;
import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.Map;
public class EnumUtils {
public static <T extends Enum<T>> Map<Integer, String> getEnumMap(Class<T> enumClass) { Map<Integer, String> enumMap = new LinkedHashMap<>();
try { Field[] fields = enumClass.getDeclaredFields();
for (Field field : fields) { if (field.isEnumConstant()) { T enumValue = Enum.valueOf(enumClass, field.getName()); int code = getCode(enumValue); String description = getDescription(enumValue); enumMap.put(code, description); } } } catch (Exception e) { e.printStackTrace(); }
return enumMap; }
private static <T extends Enum<T>> int getCode(T enumValue) { try { Field codeField = enumValue.getClass().getDeclaredField("code"); codeField.setAccessible(true); return (int) codeField.get(enumValue); } catch (Exception e) { e.printStackTrace(); return -1; } }
private static <T extends Enum<T>> String getDescription(T enumValue) { try { Field descriptionField = enumValue.getClass().getDeclaredField("description"); descriptionField.setAccessible(true); return (String) descriptionField.get(enumValue); } catch (Exception e) { e.printStackTrace(); return ""; } }
public static void main(String[] args) { Map<Integer, String> enumMap = getEnumMap(MyEnum.class); System.out.println(enumMap); }
private enum MyEnum { VALUE1(1, "Description 1"), VALUE2(2, "Description 2"), VALUE3(3, "Description 3");
private final int code; private final String description;
MyEnum(int code, String description) { this.code = code; this.description = description; } } }
|