今天在开发的时候遇到一个判断需求:判断一个值是否属于枚举类。之前写的话都是通过在if里面写上|| 或来连接 或者为每个枚举Enum写一个遍历判断的方法。后来想了一下实在太麻烦了,加入枚举类改变的话业务代码的判断也需要改变比较麻烦,工具类也没找到相关的,于是自己通过反射写了一个循环遍历判断枚举类。
首先,是一个枚举类:
public enum AuditState {
TO_BE_AUDIT(0, "待审核"),
AUDITED(1, "已审核");
private String message;
private Integer code;
AuditState(Integer code, String message) {
this.message = message;
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
然后是一个EnumUtil类:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author wayleung
* @description 枚举工具类
* @date 2020-06-08
*/
public class EnumUtils {
/**
* 判断数值是否属于枚举类的值
* @param clzz 枚举类 Enum
* @param code
* @author wayleung
* @return
*/
public static boolean isInclude(Class<?> clzz,Integer code) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
boolean include = false;
if(clzz.isEnum()){
Object[] enumConstants = clzz.getEnumConstants();
Method getCode = clzz.getMethod("getCode");
for (Object enumConstant:enumConstants){
if (getCode.invoke(enumConstant).equals(code)) {
include = true;
break;
}
}
}
return include;
}
public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
System.out.println(isInclude(BusinessGroupBuyEnum.AuditState.class,0));
System.out.println(isInclude(BusinessGroupBuyEnum.AuditState.class,1));
System.out.println(isInclude(BusinessGroupBuyEnum.AuditState.class,-1));
System.out.println(isInclude(BusinessGroupBuyEnum.AuditState.class,null));
}
}
返回的结果是:
true
true
false
false
通过测试!