Java enumeration to list generic class
1. Purpose
Implement enumeration to list
Convert to as follows:
[ { "name": "PC backend", "value": 1 }, { "name": "Main-terminal application", "value": 2 } ]
2. Enumeration class
public class SysRoleEnum { /** * Platform Type */ @Getter @AllArgsConstructor public enum PlatformTypeEnum implements ICommonEnum { pcBackground(1, "PC backend"), customerSystem(2, "Main-terminal application"); private Integer value; private String name; } }
3. Solution
Java enumeration class to List<Map<String, Object>> Collection general class
import .slf4j.Slf4j; import .; import ; import ; import ; import .*; @Slf4j public class EnumUtil { /** * Java enumeration class to List<Map<String, Object>> collection * * @param enumClass * @return null-The class is not an enum type []-The enum type has no custom fields list-get List<Map> of the enum type returns the result */ public static List<Map<String, Object>> enumToListMap(Class<?> enumClass) { List<Map<String, Object>> resultList = new ArrayList<>(); if (!"".equals(().getCanonicalName())) { return resultList; } // Get all public methods Method[] methods = (); List<Field> fieldList = new ArrayList<>(); // step 1: Extract fields through get method, so avoid get as the beginning of a custom method. It is recommended to use 'find' or other naming (methods).map(Method::getName).filter( methodName -> ("get") && !"getDeclaringClass".equals(methodName) && !"getClass".equals(methodName) ).forEachOrdered(methodName -> { try { Field field = (((3))); (field); } catch (NoSuchFieldException | SecurityException e) { ((), e); } }); // step 2: Use the field as key and store the enumeration value as value into the list one by one if ((fieldList)) { return resultList; } Enum[] enums = (Enum[]) (); for (Enum anEnum : enums) { Map<String, Object> map = new HashMap<>(()); for (Field field : fieldList) { (true); try { // Add field names and field values to map collection ((), (anEnum)); } catch (IllegalArgumentException | IllegalAccessException e) { ((), e); } } // Add Map to the collection (map); } return resultList; } }
How to use
();
Request to display
[ { "name": "PC backend", "value": 1 }, { "name": "Main-terminal application", "value": 2 } ]
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.