Java反射遍历判断值是否属于枚举类Enum

发布时间 2024-01-10 11:25:22作者: chelsey3tsf
首先,是一个枚举类:
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

通过测试!