根据值获取枚举类对象工具类EnumUtils
枚举类
public enum Sex { man("M","男"),woman("W","女"); private String myCode; private String value; private Sex(String myCode, String value) { this.myCode = myCode; this.value = value; } public String getMyCode() { return myCode; } public void setMyCode(String myCode) { this.myCode = myCode; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
公共工具类
/** * https://blog.csdn.net/u010125873/article/details/81386320 * @author admin */ public class EnumUtils { private static Map<Class,Object> map = new ConcurrentHashMap<>(); /** * 根据条件获取枚举对象 * @param className 枚举类 * @param predicate 筛选条件 * @param <T> * @return */ @SuppressWarnings("unchecked") public static <T> Optional<T> getEnumObject(Class<T> className, Predicate<T> predicate) { if(!className.isEnum()){ // logger.info("Class 不是枚举类"); return null; } Object obj = map.get(className); T[] ts = null; if(obj == null){ ts = className.getEnumConstants(); map.put(className,ts); }else{ ts = (T[])obj; } return Arrays.stream(ts).filter(predicate).findAny(); } public static void main(String[] args) { Optional<Sex> m = EnumUtils.getEnumObject(Sex.class, e -> e.getMyCode().equals("W")); System.out.println(m.isPresent() ? m.get().getValue():null); } }
特点:
1)能自动获取枚举类中的方法,如e.getMyCode()和m.get().getValue()
参考:https://blog.csdn.net/u010125873/article/details/81386320
另外一种通过反射实现:
public class EnumHelperUtil{ /** * 使用枚举类型对应的typeName获取枚举类型 * @param clazz 枚举类的class * @param getTypeNameMethodName 传入的typeName的get方法 * @param typeName 传入的typeName值,这个方法为Object类型 */ public static <T extends Enum<T>> T getEnumsValue(Class<T> clazz,String getTypeNameMethodName, Object typeName){ T result = null; try{ T[] arr = clazz.getEnumConstants(); Method targetMethod = clazz.getDeclaredMethod(getTypeNameMethodName); Object typeNameVal = null; for(T entity:arr){ typeNameVal = targetMethod.invoke(entity); if(typeNameVal.equals(typeName)){ result = entity; break; } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return result; } public static void main(String[] args) { Sex byStringTypeName = EnumHelperUtil.getEnumsValue(Sex.class, "getMyCode", 1); System.out.println(byStringTypeName.getValue()); } }
链接:https://blog.csdn.net/busbanana/article/details/72954676
注意:原文中提供了Integer和String的2种方法,而本例统一转为Object,只提供一个方法。