其他分享
首页 > 其他分享> > Assert

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);
        }
    }
}

标签:code,void,object,Assert,static,notNull,public
来源: https://blog.csdn.net/weixin_56689825/article/details/120763001