learning_record_doc/java/Java 通过反射获取枚举对象.md
2022-02-28 23:07:00 +08:00

1.3 KiB
Raw Blame History

/**
 * @author dss
 * @date 2021/10/9
 * @description:
 */
public enum AuditStatus{

    NO_SUBJECT(0,"未提交"),
    NO_AUDIT(2,"未审核"),
    AUDIT(1,"审核通过");


    @Getter
    private final Integer code;

    @Getter
    private final String label;

    AuditStatus(Integer code,String label){
        this.code=code;
        this.label=label;
    }


    /**
     * 根据code获取对应的label
     * @param code 
     * @return 形参code所对应的label值
     * @throws Exception
     */
    public static String getValueByCode(Integer code) throws Exception {
        //获取Class对象
        Class<?> clzz = AuditStatus.class;

        // 获取所有枚举对象
        Object[] objects = clzz.getEnumConstants();
        //获取指定方法
        Method coinLabel = clzz.getMethod("getLabel");
        Method coinCode = clzz.getMethod("getCode");


        //遍历所有枚举对象
        for (Object obj : objects) {
            //执行coinCode方法(getCode)该枚举的code值如果和形参code 的值相同则
            if (coinCode.invoke(obj) == code) {
                //执行coinLabel方法getLabel获取响应的label值进行返回
                return coinLabel.invoke(obj).toString();
            }
        }
        return null;
    }
}