Write an enumUtil tool class to get the [enumeration value] [enumeration list] of the Enum enumeration object

Premise: Using a long string of String collections is not as convenient and fast as directly writing an enumeration and then obtaining the enumeration value, and it is not easy to make mistakes. (A total of 30 payment types, ↓ is the previous wording of "Yuan XX", I changed it to get the enumeration set (the original related enumeration class))
insert image description here

Implementation code

package com.yami.shop.util;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * enum工具类-哒不溜
 */
public class EnumUtil {
    
    
    private static final String ENUM_CLASSPATH ="java.lang.Enum";

    /**
     * 获取枚举列表
     * @param enumClass 枚举类.class
     * @return
     */
    public static List<Map<String, Object>> enumToListMap(Class<?> enumClass) {
    
    
        List<Map<String, Object>> resultList= new ArrayList<>();
        if (!ENUM_CLASSPATH.equals(enumClass.getSuperclass().getCanonicalName())) {
    
    
            return resultList;
        }
        // 获取所有public方法
        Method[] methods = enumClass.getMethods();
        List<Field> fieldList = new ArrayList<>();
        //1.通过get方法提取字段,避免get作为自定义方法的开头,建议使用 ‘find’或其余命名
        Arrays.stream(methods)
                .map(Method::getName)
                .filter(
                        methodName -> methodName.startsWith("get") && !"getDeclaringClass".equals(methodName) && !"getClass".equals(methodName)
                ).forEachOrdered(methodName -> {
    
    
                    try {
    
    
                        Field field = enumClass.getDeclaredField(StringUtils.uncapitalize(methodName.substring(3)));
                        fieldList.add(field);
                    } catch (NoSuchFieldException | SecurityException e) {
    
    
                        e.printStackTrace();
                    }
                });

        //2.将字段作为key,逐一把枚举值作为value 存入list
        if (CollectionUtils.isEmpty(fieldList)) {
    
    
            return resultList;
        }

        Enum[] enums = (Enum[]) enumClass.getEnumConstants();
        for (Enum anEnum : enums) {
    
    
            Map<String, Object> map = new HashMap<>(fieldList.size());
            for (Field field : fieldList) {
    
    
                field.setAccessible(true);
                try {
    
    
                    // 向map集合添加字段名称 和 字段值
                    map.put(field.getName(), field.get(anEnum));
                } catch (IllegalArgumentException | IllegalAccessException e) {
    
    
                    e.printStackTrace();
                }
            }
            // 将Map添加到集合中
            resultList.add(map);
        }
        return resultList;
    }

// 下面这个方法是直接复制上面 然后就修改了返回结果,没有细看前面 应该还可以省略些代码
    /**
     * 只返回枚举的值 
     * @param enumClass
     * @return
     */
    public static List<String> enumValueToList(Class<?> enumClass) {
    
    
        List<String> resultList= new ArrayList<>();
        if (!ENUM_CLASSPATH.equals(enumClass.getSuperclass().getCanonicalName())) {
    
    
            return resultList;
        }
        // 获取所有public方法
        Method[] methods = enumClass.getMethods();
        List<Field> fieldList = new ArrayList<>();
        //1.通过get方法提取字段,避免get作为自定义方法的开头,建议使用 ‘find’或其余命名
        Arrays.stream(methods)
                .map(Method::getName)
                .filter(
                        methodName -> methodName.startsWith("get") && !"getDeclaringClass".equals(methodName) && !"getClass".equals(methodName)
                ).forEachOrdered(methodName -> {
    
    
                    try {
    
    
                        Field field = enumClass.getDeclaredField(StringUtils.uncapitalize(methodName.substring(3)));
                        fieldList.add(field);
                    } catch (NoSuchFieldException | SecurityException e) {
    
    
                        e.printStackTrace();
                    }
                });

        //2.将字段作为key,逐一把枚举值作为value 存入list
        if (CollectionUtils.isEmpty(fieldList)) {
    
    
            return resultList;
        }

        Enum[] enums = (Enum[]) enumClass.getEnumConstants();
        for (Enum anEnum : enums) {
    
    
            for (Field field : fieldList) {
    
    
                field.setAccessible(true);
                try {
    
    
                    resultList.add(field.get(anEnum)+"");
                } catch (IllegalArgumentException | IllegalAccessException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        return resultList;
    }
}

transfer

// 参数传入枚举类.class 就行
List<Map<String, Object>> maps = EnumUtil.enumToListMap(PayType.class);

List<String> payList = EnumUtil.enumValueToList(PayType.class);
// list转String数组
String[] payTypes = payList.toArray(new String[payList.size()]);

Let's do this first, I don't know what to write

Guess you like

Origin blog.csdn.net/weixin_43825761/article/details/128560588