这是一个枚举工具类,有时候一个枚举自身为空,我们程序在调用他的方法时(如:name(),ordinal()),就会报空指针异常;下面写这个工具类就是为了来避免这些问题的,有些外部引用的没有贴出来,不过都是些挺简单的工具代码;
代码如下:
/* * Copyright 2014-2018 xfami.cn. All rights reserved. * Support: https://www.xfami.cn */ package com.cymc.page.common.enumobj; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.util.Assert; import com.cymc.page.admin.autocar.enums.param.AutoCarInteriorColorEnum; import com.cymc.page.common.CommonAttrs; import com.cymc.page.common.CommonUtil; import com.cymc.page.utils.SpringUtils; /** * Utils - 枚举工具 * * @author XFaMi Team * @version 1.0 * @CreateDate 2018-1-16 下午2:41:41 */ public class EnumUtils { public final static String CLASS_NAME_ENUM = "Enum"; private final static String METHOD_GET = "get"; private EnumUtils() { } public static void main(String[] args) { //getEnumJsonBean(AutoCarInteriorColorEnum.class, "nihao"); //System.out.println(enumToMap(AutoCarInteriorColorEnum.class, null)); //AutoCarInteriorColorEnum c = null; System.out.println(getEnumPropMap(AutoCarInteriorColorEnum.beige)); //System.out.println(getEnumOrdinal(AutoCarInteriorColorEnum.red)); } /** * 获取枚举 getLabel(获取中文翻译)方法的返回值 * 此方法去调用枚举中的'getLabel'方法 * @param e 如果为null 返回空字符串"" * @return */ @SuppressWarnings("rawtypes") public static String getLabel(Enum e) { if (e == null) { return StringUtils.EMPTY; } try { Method method = e.getClass().getMethod("getLabel"); return (String) method.invoke(e); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) { e1.printStackTrace(); } return StringUtils.EMPTY; } /** * 获取枚举 getLabel(获取中文翻译)方法的返回值 * 此方法直接获取account_zh_CN.properties配置文件中的翻译 * @param e 如果为null 返回空字符串"" * @return */ @SuppressWarnings("rawtypes") public static String getLabelV2(Enum e) { if (e == null) { return StringUtils.EMPTY; } return SpringUtils.getMessage(e.getClass().getSimpleName().replace(EnumUtils.CLASS_NAME_ENUM, StringUtils.EMPTY) + CommonAttrs.SPLITTER_SPOT + e.name()); } /** * 获取枚举下标,如果枚举为null,也返回null * @param e * @return */ @SuppressWarnings("rawtypes") public static Integer getEnumOrdinal(Enum e) { if (e == null) { return null; } return e.ordinal(); } /** * 获取枚举属性 及对应值 * @param ordinal * @param clazz * @return */ public static <T> Map<String, Object> getEnumMapByOrdinal(Integer ordinal, Class<T> clazz) { if (ordinal == null || clazz == null || !clazz.isEnum()) { return null; } Map<String, Object> data = new HashMap<String, Object>(); // 获取 枚举的属性字段 和 get方法 Map<String, String> propData = new HashMap<String, String>(); for (Field field : clazz.getDeclaredFields()) { if (field.getModifiers() == 2 || field.getModifiers() == 18) { propData.put(field.getName(), METHOD_GET + CommonUtil.firstLetterUpper(field.getName())); } } T obj = clazz.getEnumConstants()[ordinal]; data.put("ordinal", ordinal); data.put("name", obj.toString()); for (Map.Entry<String, String> entry : propData.entrySet()) { try { Method method = clazz.getMethod(entry.getValue()); data.put(entry.getKey(), method.invoke(obj)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } return data; } /** * 获取枚举属性 及对应值 * @param en * @return */ @SuppressWarnings("rawtypes") public static Map<String, Object> getEnumPropMap(Enum en) { if (en == null) { return null; } // 获取 枚举的属性字段 和 get方法 Map<String, String> propData = new HashMap<String, String>(); for (Field field : en.getClass().getDeclaredFields()) { if (field.getModifiers() == 2 || field.getModifiers() == 18) { propData.put(field.getName(), METHOD_GET + CommonUtil.firstLetterUpper(field.getName())); } } // 单独处理 getLabel 方法 for (int i = 0; i < en.getClass().getInterfaces().length; i++) { Class<?> s = en.getClass().getInterfaces()[i]; if (s.equals(EnumsLabelInterface.class) || s.equals(EnumsCodeInterface.class)) { propData.put("label", "getLabel"); } } Map<String, Object> data = new HashMap<String, Object>(); data.put("ordinal", en.ordinal()); data.put("name", en.name()); for (Map.Entry<String, String> entry : propData.entrySet()) { try { Method method = en.getClass().getMethod(entry.getValue()); data.put(entry.getKey(), method.invoke(en)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } return data; } @Deprecated public static <T> EnumJsonBean getEnumJsonBean(Class<T> clazz, String enumObjLabel) { Assert.notNull(clazz); String sname = clazz.getSimpleName().replace(CLASS_NAME_ENUM, StringUtils.EMPTY); sname = CommonUtil.toLowerCaseFirstOne(sname); return getEnumJsonBean(clazz, sname, enumObjLabel); } /** * * @param clazz * @param enumObjName * @param enumObjLabel * @return */ @Deprecated public static <T> EnumJsonBean getEnumJsonBean(Class<T> clazz, String enumObjName, String enumObjLabel) { Assert.hasText(enumObjName); Assert.hasText(enumObjLabel); Assert.notNull(clazz); if (!clazz.isEnum()) { return null; } // 获取 枚举的属性字段 和 get方法 Map<String, String> propData = new HashMap<String, String>(); for (Field field : clazz.getDeclaredFields()) { if (field.getModifiers() == 2 || field.getModifiers() == 18) { propData.put(field.getName(), METHOD_GET + CommonUtil.firstLetterUpper(field.getName())); } } // 单独处理 getLabel 方法 for (int i = 0; i < clazz.getInterfaces().length; i++) { Class<?> s = clazz.getInterfaces()[i]; if (s.equals(EnumsLabelInterface.class) || s.equals(EnumsCodeInterface.class)) { propData.put("label", "getLabel"); } } // 生成EnumJsonBean EnumJsonBean enumJson = new EnumJsonBean(enumObjName, enumObjLabel); T[] objs = clazz.getEnumConstants(); for (int i = 0; i < objs.length; i++) { Map<String, Object> data = new HashMap<String, Object>(); data.put("ordinal", i); data.put("name", objs[i].toString()); for (Map.Entry<String, String> entry : propData.entrySet()) { try { Method method = clazz.getMethod(entry.getValue()); data.put(entry.getKey(), method.invoke(objs[i])); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } enumJson.getItems().add(data); } return enumJson; } /** * 将枚举对象转为 map对象 * @param clazz * @param enumObjName * @param enumObjLabel * @param srcData * @return */ public static <T> Map<String, Object> enumToMap(Class<T> clazz, Map<String, Object> srcData) { Assert.notNull(clazz); if (!clazz.isEnum()) { return null; } if (srcData == null) { srcData = new HashMap<>(); } // 生成map Key String sname = clazz.getSimpleName().replace(CLASS_NAME_ENUM, StringUtils.EMPTY); sname = CommonUtil.toLowerCaseFirstOne(sname); // 放值 srcData.put(sname, getEnumValues(clazz)); return srcData; } /** * 获取枚举所有值的属性 * @param clazz * @return */ public static <T> List<Map<String, Object>> getEnumValues(Class<T> clazz) { Assert.notNull(clazz); if (!clazz.isEnum()) { return null; } // 获取 枚举的属性字段 和 get方法 Map<String, String> propData = new HashMap<String, String>(); for (Field field : clazz.getDeclaredFields()) { if (field.getModifiers() == 2 || field.getModifiers() == 18) { propData.put(field.getName(), METHOD_GET + CommonUtil.firstLetterUpper(field.getName())); } } // 单独处理 getLabel 方法 for (int i = 0; i < clazz.getInterfaces().length; i++) { Class<?> s = clazz.getInterfaces()[i]; if (s.equals(EnumsLabelInterface.class) || s.equals(EnumsCodeInterface.class)) { propData.put("label", "getLabel"); } } // 生成map value List<Map<String, Object>> dataList = new ArrayList<>(); T[] objs = clazz.getEnumConstants(); for (int i = 0; i < objs.length; i++) { Map<String, Object> data = new HashMap<String, Object>(); data.put("ordinal", i); data.put("name", objs[i].toString()); for (Map.Entry<String, String> entry : propData.entrySet()) { try { Method method = clazz.getMethod(entry.getValue()); data.put(entry.getKey(), method.invoke(objs[i])); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } dataList.add(data); } return dataList; } /** * 通过Class获取枚举对象EnumObjBean * 弃用 * @param clazz * @param enumObjName * @param enumObjLabel * @return */ @Deprecated public static EnumObjBean getEnumObjBean(Class<?> clazz, String enumObjName, String enumObjLabel) { Assert.hasText(enumObjName); Assert.hasText(enumObjLabel); Assert.notNull(clazz); EnumObjBean enumObj = new EnumObjBean(enumObjName, enumObjLabel); Object[] objs = clazz.getEnumConstants(); for (int i = 0; i < objs.length; i++) { // System.out.println(i + objs[i].toString()); // EnumBean bean = new EnumBean(i, objs[i].toString(), SpringUtils.getMessage("CarParm." // + CommonUtil.firstLetterUpper(enumObjName) + CommonAttrs.SPLITTER_SPOT + objs[i].toString())); EnumBean bean = new EnumBean(i, objs[i].toString(), "中文意思"); enumObj.getEnums().add(bean); } return enumObj; } /** * 通过下标 获取枚举 * @param <T> * * @param clazz * @param ordinal * @return */ public static <T> T getEnumByOrdinal(Class<T> clazz, Integer ordinal) { if (clazz == null || ordinal == null || !clazz.isEnum()) { return null; } T[] objs = (T[]) clazz.getEnumConstants(); if (ordinal < 0 || ordinal >= objs.length) { return null; } return objs[ordinal]; } /** * 通过code 获取枚举 * 枚举必须有code值,枚举类必须有getCode()方法 * 不建议使用 * @param clazz * @param code * @return */ public static <T> T getEnumByCode(Class<T> clazz, String code) { if (clazz == null || StringUtils.isBlank(code) || !clazz.isEnum()) { return null; } T[] objs = (T[]) clazz.getEnumConstants(); for (int i = 0; i < objs.length; i++) { try { Method m = clazz.getMethod("getCode"); if (code.equals(m.invoke(objs[i]))) { return objs[i]; } } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); return null; } } return null; } /** * 通过code 获取枚举 * 枚举必须有code值,枚举类必须有getCode()方法 * 不建议使用 * @param clazz * @param code * @return */ public static <T> T getEnumByCode(Class<T> clazz, Integer code) { if (clazz == null || code == null || !clazz.isEnum()) { return null; } T[] objs = (T[]) clazz.getEnumConstants(); for (int i = 0; i < objs.length; i++) { try { Method m = clazz.getMethod("getCode"); if (code == m.invoke(objs[i])) { return objs[i]; } } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); return null; } } return null; } }
代码中
CommonAttrs.SPLITTER_SPOT = “.”
CommonUtil.firstLetterUpper(xxx) 字符串首字母 转大写
/** * 字符串首字母 转大写 * @param str * @return */ public static String firstLetterUpper(String str) { Assert.hasText(str); char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') { ch[0] = (char) (ch[0] - 32); } return String.valueOf(ch); }
CommonUtil.toLowerCaseFirstOne(xxx) 首字母转小写
测试补充代码:
/* * Copyright 2014-2018 xfami.cn. All rights reserved. * Support: https://www.xfami.cn */ package com.cymc.page.admin.autocar.enums.param; import com.cymc.page.common.enumobj.EnumsLabelInterface; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; /** * Enum - 内饰颜色 * * @author XFaMi Team * @version 1.0 * @CreateDate 2018-1-12 下午5:21:13 */ @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum AutoCarInteriorColorEnum implements EnumsLabelInterface { /** 米黄 */ beige("米黄", "#f7eed5"), /** 米灰 */ griege("米灰", "#cccccc"), /** 红色 */ red("红色", "#ec111a"), /** 黑色 */ black("黑色", "#000000"), /** 棕色 */ brown("棕色", "#724623"), /** 其他 */ other("其他", "#ffffff"), ; /** 中文标记 */ private final String label; /** 颜色值 */ private final String value; private AutoCarInteriorColorEnum(String label, String value) { this.label = label; this.value = value; } @Override public String getLabel() { return label; } public String getValue() { return value; } @JsonProperty("name") public String getName(){ return name(); } @JsonProperty("ordinal") public int getOrdinal(){ return ordinal(); } }
@JsonFormat 是SpringMVC jackson的注解,为了方便将@ResponseBody返回枚举对象是一个map键值对类型的json数据;