All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.chobit.common.validation.EnumValueValidator Maven / Gradle / Ivy

The newest version!
package org.chobit.common.validation;


import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.chobit.common.base.BaseEnum;
import org.chobit.common.utils.BaseEnumKit;

/**
 * 枚举值验证
 *
 * @author robin
 */
public class EnumValueValidator implements ConstraintValidator {


    /**
     * 枚举类型
     */
    private Class> enumClass;

    /**
     * 已排除的枚举code值
     */
    private int[] excludeCodes;


    @Override
    public void initialize(EnumValue enumVal) {
        this.enumClass = enumVal.enumClass();
        if (!BaseEnum.class.isAssignableFrom(this.enumClass)) {
            throw new IllegalArgumentException(this.enumClass + "不是继承自BaseEnum");
        }
        this.excludeCodes = enumVal.exclude();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }

        if (null != excludeCodes && excludeCodes.length != 0) {
            for (int code : excludeCodes) {
                if (code == value) {
                    return false;
                }
            }
        }

        BaseEnum e = BaseEnumKit.enumOf(value, this.enumClass);

        return null != e;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy