今天遇到一个小问题,就是 需要做报表统计,然后自己建立的枚举名称都一致,但是每个枚举集合值不一致,所以
想弄一个专用的方法 ,不用每个枚举方法都去遍历,直接传入class名称就可以 筛选的方案,最后找资料得出以下方法,希望能帮助到大家。
关键枚举方法:
//参考EnumExtUtil 获取枚举变量的值 public static <T extends Enum<T>> int getEnumOnValue(Class<T> enumType, int value) throws Exception { for (Object obj : enumType.getEnumConstants()) { Method m = obj.getClass().getDeclaredMethod("getHigh", null); int highscore = (int) m.invoke(obj, null); m = obj.getClass().getDeclaredMethod("getLower", null); int lowerScore = (int) m.invoke(obj, null); m = obj.getClass().getDeclaredMethod("getScore", null); int score = (int) m.invoke(obj, null); if (value == -1 && lowerScore == -1) { return score; } if (value > lowerScore && value <= highscore) { return score; } } return 0; }
枚举类
enum UnionpayEnums { weirenzheng(1, "0、未认证;", 16, -1, 0), onceTime(2, "上月支付1次及以下;", 8, 0, 1), towTimes(3, "上月支付1-2次", 12, 1, 2), threeTimes(4, "上月支付3-4次;", 16, 3, 4), fiveTimes(5, "上月支付5-7次", 20, 4, 7), sixTimes(6, "上月支付7次以上", 24, 7, Integer.MAX_VALUE); private int code;//排序 private String desc;//描述 private int score;//分值 private int lower;//最低次数 private int high;//最高次数 UnionpayEnums() { } UnionpayEnums(int code, String desc, int score, int lower, int high) { this.code = code; this.desc = desc; this.score = score; this.lower = lower; this.high = high; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public int getLower() { return lower; } public void setLower(int lower) { this.lower = lower; } public int getHigh() { return high; } public void setHigh(int high) { this.high = high; } }
方法内遍历枚举
public int scores(){ for (UnionpayEnums upay:UnionpayEnums.values()){ int score =upay.getScore(); } }
拓展
//传入方法名称 values是值 ,field是 字段mingcheng public static <T extends Enum<T>> T getEnumOnValue(Class<T> enumType, String value, String field) throws Exception { for (Object obj : enumType.getEnumConstants()) { Method m = obj.getClass().getDeclaredMethod("values", null); Object[] results = (Object[]) m.invoke(obj, null); for (Object result : results) { Field codeField = result.getClass().getDeclaredField(field); ReflectionUtils.makeAccessible(codeField); String fileValue = String.valueOf(ReflectionUtils.getField(codeField, result)); if (fileValue.equals(value)) { return (T) result; } } } return null; }
AbilityEnum abilityEnum = EnumExtUtil.getEnumOnValue(AbilityEnum.class, String.valueOf(maxAbility.getAbilityId()), "code");
利用这个方法,可以直接拿到枚举类 某一条对象的集合