import java.util.Objects; import java.util.function.BooleanSupplier; /** * 自定义的校验工具类 * 可以根据不同的条件进行检查,并在条件不满足时抛出异常 * * @author wangqingpan * @since 2025-1-13 */ public class CustomCheckUtils { private CustomCheckUtils() { } /** * 如果对象为 null,抛出异常 * * @param obj 被检测的对象 * @param message 异常信息 */ public static void throwIfNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } } /** * 如果对象不为 null,抛出异常 * * @param obj 被检测的对象 * @param message 异常信息 */ public static void throwIfNotNull(Object obj, String message) { if (obj != null) { throw new IllegalArgumentException(message); } } /** * 如果字符串为空,抛出异常 * * @param str 被检测的字符串 * @param message 异常信息 */ public static void throwIfEmpty(String str, String message) { if (str == null || str.isEmpty()) { throw new IllegalArgumentException(message); } } /** * 如果字符串不为空,抛出异常 * * @param str 被检测的字符串 * @param message 异常信息 */ public static void throwIfNotEmpty(String str, String message) { if (str != null && !str.isEmpty()) { throw new IllegalArgumentException(message); } } /** * 如果字符串为 blank(只包含空格或为空),抛出异常 * * @param str 被检测的字符串 * @param message 异常信息 */ public static void throwIfBlank(String str, String message) { if (str == null || str.trim().isEmpty()) { throw new IllegalArgumentException(message); } } /** * 如果字符串不为 blank,抛出异常 * * @param str 被检测的字符串 * @param message 异常信息 */ public static void throwIfNotBlank(String str, String message) { if (str != null && !str.trim().isEmpty()) { throw new IllegalArgumentException(message); } } /** * 如果两个对象相等,抛出异常 * * @param obj1 要比较的对象 1 * @param obj2 要比较的对象 2 * @param message 异常信息 */ public static void throwIfEqual(Object obj1, Object obj2, String message) { if (Objects.equals(obj1, obj2)) { throw new IllegalArgumentException(message); } } /** * 如果两个对象不相等,抛出异常 * * @param obj1 要比较的对象 1 * @param obj2 要比较的对象 2 * @param message 异常信息 */ public static void throwIfNotEqual(Object obj1, Object obj2, String message) { if (!Objects.equals(obj1, obj2)) { throw new IllegalArgumentException(message); } } /** * 如果条件为 true,抛出异常 * * @param condition 条件 * @param message 异常信息 */ public static void throwIf(boolean condition, String message) { if (condition) { throw new IllegalArgumentException(message); } } /** * 如果条件供应商提供的条件为 true,抛出异常 * * @param conditionSupplier 条件供应商 * @param message 异常信息 */ public static void throwIf(BooleanSupplier conditionSupplier, String message) { if (conditionSupplier.getAsBoolean()) { throw new IllegalArgumentException(message); } } }
Java自定义校验工具类
最新推荐文章于 2025-01-19 11:12:09 发布