枚举工具类 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172package 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(); // 处理异常,例如 NoSuchFieldException 或 SecurityException } 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; } }}