写一个enumUtil工具类,获取Enum枚举对象的【枚举值】【枚举列表】

前提:用着一大长串的String集合不如 直接写个枚举 然后获取枚举的值来的方便快捷,也不容易出错。(整整快30种支付类型,↓是之前‘元某人’写法,我改成了获取枚举集合(原有相关枚举类))
在这里插入图片描述

实现代码

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;
    }
}

调用

// 参数传入枚举类.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()]);

先这样吧,不知道写什么

猜你喜欢

转载自blog.csdn.net/weixin_43825761/article/details/128560588