Assert

import com.yunrui.starter.exception.BizException;
import com.yunrui.starter.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;


public class Assert {
    public static final Logger log = LoggerFactory.getLogger(Assert.class);

    /**
     * 校验参数
     */
    public static void vailParams(Object... objects) {
        notNull(objects, Code.InnerCode.ERR_PARAM);
    }

    /**
     * object不为null,否则抛出ZmException
     */
    public static void notNull(Object object) {
        if (StringUtils.isEmpty(object)) {
            throw new BizException(Code.InnerCode.ERR_PARAM);
        }
    }

    /**
     * object不为null,否则抛出ZmException
     */
    public static void notNull(Object object, Code code) {
        if (StringUtils.isEmpty(object)) {
            throw new BizException(code);
        }
    }

    /**
     * object不为null,否则抛出ZmException
     */
    public static void notNull(Object object1, Object object2, Code code) {
        notNull(object1, code);
        notNull(object2, code);
    }


    public static void notNull(Object object, String name) {
        if (StringUtils.isEmpty(object)) {
            throw new BizException(name);
        }
    }

    /**
     * 判断是否为true  false抛出异常信息
     *
     * @param boole
     * @param name
     */
    public static void isTrue(Boolean boole, String name) {
        if (!boole) {
            throw new BizException(name);
        }
    }

    /**
     * 判断是否为true  false抛出异常信息
     *
     * @param boole
     * @param code
     */
    public static void isTrue(Boolean boole, Code code) {
        if (!boole) {
            throw new BizException(Result.ins(code));
        }
    }

    public static void validateParams(Object obj, String... args) {
        if (obj == null) {
            return;
        }
        try {
            Class<?> clazz = obj.getClass();
            for (String arg : args) {
                Field field = clazz.getDeclaredField(arg);
                field.setAccessible(true);
                if (StringUtils.isEmpty(field.get(obj))) {
                    throw new BizException(Code.InnerCode.ERR_PARAM.getCode(), String.format("缺少参数[%s]", field.getName()));
                }
            }
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}

上一篇:编写一个IDEA插件之:事件监听


下一篇:Spring 中@NotNull, @NotEmpty和@NotBlank之间的区别是什么?