Spring工具类之Assert的使用

Spring工具类之Assert的使用

作用:帮忙做参数检验并抛出IllegalArgumentException

抛出的都是IllegalArgumentException异常

  1. 根据boolean表达式的值抛出异常信息isTrue
  2. 判断对象是否为空isNull或不为空notNull
  3. 判断字符串是否null或”有N个空都是空” hasText
  4. 判断字符串是否包含另外一个字符串

doesNotContain(@Nullable String textToSearch, String substring, String message)

  1. 判断一个数组是否null或长度为0  notEmpty
  2. 判断一个数组的元素是否有null,只要有null就抛异常  noNullElements
  3. 判断一个集合不为空,为null或长度为0抛出异常
  4. 判断一个对象是否是某个类的实例isInstanceOf
  5. 使用isAssignable方法判断2个类是否是父子类
  6. 安全获取String
@Nullable

private static String nullSafeGet(@Nullable Supplier<String> messageSupplier) {

    return messageSupplier != null ? (String)messageSupplier.get() : null;

}

 

 

  1. Assert.hasText(“如果为空或null”,”抛出的异常信息”);

说明:当第1个参数为null或””或” 有空格或有N个空格”,抛出IllegalArgumentException异常,此异常是运行时异常。异常信息为第2个参数

public static void main(String[] args) {
//        Assert.hasText(null, "输入信息错误!");
//        Assert.hasText("", "输入信息错误!");
//        Assert.hasText(" ", "输入信息错误!");
       
Assert.hasText("   ", "输入信息错误!");
       
System.out.println("执行了吗? 没有");
   
}

  1. Assert.notNull(null, "object is required");// 第一个参数为null抛IllegalArgumentException
  2. Assert.isTrue(Object object, "object must be true")   -    对象必须为true  
  3. Assert.notEmpty(Collection collection, "collection must not be empty")    -    集合非空 
  4. Assert.hasLength(String text, "text must be specified")   -    字符不为null且字符长度不为0  

Assert.hasText(String text, "text must not be empty")    -     text 不为null且必须至少包含一个非空格的字符 

Assert.isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]")    -    obj必须能被正确造型成为clazz 指定的类

 

public abstract class Assert {

    public Assert() {

    }



    public static void state(boolean expression, String message) {

        if (!expression) {

            throw new IllegalStateException(message);

        }

    }



    public static void state(boolean expression, Supplier<String> messageSupplier) {

        if (!expression) {

            throw new IllegalStateException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void state(boolean expression) {

        state(expression, "[Assertion failed] - this state invariant must be true");

    }



    public static void isTrue(boolean expression, String message) {

        if (!expression) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void isTrue(boolean expression, Supplier<String> messageSupplier) {

        if (!expression) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void isTrue(boolean expression) {

        isTrue(expression, "[Assertion failed] - this expression must be true");

    }



    public static void isNull(@Nullable Object object, String message) {

        if (object != null) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void isNull(@Nullable Object object, Supplier<String> messageSupplier) {

        if (object != null) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void isNull(@Nullable Object object) {

        isNull(object, "[Assertion failed] - the object argument must be null");

    }



    public static void notNull(@Nullable Object object, String message) {

        if (object == null) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void notNull(@Nullable Object object, Supplier<String> messageSupplier) {

        if (object == null) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void notNull(@Nullable Object object) {

        notNull(object, "[Assertion failed] - this argument is required; it must not be null");

    }



    public static void hasLength(@Nullable String text, String message) {

        if (!StringUtils.hasLength(text)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void hasLength(@Nullable String text, Supplier<String> messageSupplier) {

        if (!StringUtils.hasLength(text)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void hasLength(@Nullable String text) {

        hasLength(text, "[Assertion failed] - this String argument must have length; it must not be null or empty");

    }



    public static void hasText(@Nullable String text, String message) {

        if (!StringUtils.hasText(text)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void hasText(@Nullable String text, Supplier<String> messageSupplier) {

        if (!StringUtils.hasText(text)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void hasText(@Nullable String text) {

        hasText(text, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank");

    }



    public static void doesNotContain(@Nullable String textToSearch, String substring, String message) {

        if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void doesNotContain(@Nullable String textToSearch, String substring, Supplier<String> messageSupplier) {

        if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) && textToSearch.contains(substring)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void doesNotContain(@Nullable String textToSearch, String substring) {

        doesNotContain(textToSearch, substring, () -> {

            return "[Assertion failed] - this String argument must not contain the substring [" + substring + "]";

        });

    }



    public static void notEmpty(@Nullable Object[] array, String message) {

        if (ObjectUtils.isEmpty(array)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void notEmpty(@Nullable Object[] array, Supplier<String> messageSupplier) {

        if (ObjectUtils.isEmpty(array)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void notEmpty(@Nullable Object[] array) {

        notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element");

    }



    public static void noNullElements(@Nullable Object[] array, String message) {

        if (array != null) {

            Object[] var2 = array;

            int var3 = array.length;



            for(int var4 = 0; var4 < var3; ++var4) {

                Object element = var2[var4];

                if (element == null) {

                    throw new IllegalArgumentException(message);

                }

            }

        }



    }



    public static void noNullElements(@Nullable Object[] array, Supplier<String> messageSupplier) {

        if (array != null) {

            Object[] var2 = array;

            int var3 = array.length;



            for(int var4 = 0; var4 < var3; ++var4) {

                Object element = var2[var4];

                if (element == null) {

                    throw new IllegalArgumentException(nullSafeGet(messageSupplier));

                }

            }

        }



    }



    /** @deprecated */

    @Deprecated

    public static void noNullElements(@Nullable Object[] array) {

        noNullElements(array, "[Assertion failed] - this array must not contain any null elements");

    }



    public static void notEmpty(@Nullable Collection<?> collection, String message) {

        if (CollectionUtils.isEmpty(collection)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void notEmpty(@Nullable Collection<?> collection, Supplier<String> messageSupplier) {

        if (CollectionUtils.isEmpty(collection)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void notEmpty(@Nullable Collection<?> collection) {

        notEmpty(collection, "[Assertion failed] - this collection must not be empty: it must contain at least 1 element");

    }



    public static void notEmpty(@Nullable Map<?, ?> map, String message) {

        if (CollectionUtils.isEmpty(map)) {

            throw new IllegalArgumentException(message);

        }

    }



    public static void notEmpty(@Nullable Map<?, ?> map, Supplier<String> messageSupplier) {

        if (CollectionUtils.isEmpty(map)) {

            throw new IllegalArgumentException(nullSafeGet(messageSupplier));

        }

    }



    /** @deprecated */

    @Deprecated

    public static void notEmpty(@Nullable Map<?, ?> map) {

        notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");

    }



    public static void isInstanceOf(Class<?> type, @Nullable Object obj, String message) {

        notNull(type, (String)"Type to check against must not be null");

        if (!type.isInstance(obj)) {

            instanceCheckFailed(type, obj, message);

        }



    }



    public static void isInstanceOf(Class<?> type, @Nullable Object obj, Supplier<String> messageSupplier) {

        notNull(type, (String)"Type to check against must not be null");

        if (!type.isInstance(obj)) {

            instanceCheckFailed(type, obj, nullSafeGet(messageSupplier));

        }



    }



    public static void isInstanceOf(Class<?> type, @Nullable Object obj) {

        isInstanceOf(type, obj, "");

    }



    public static void isAssignable(Class<?> superType, @Nullable Class<?> subType, String message) {

        notNull(superType, (String)"Super type to check against must not be null");

        if (subType == null || !superType.isAssignableFrom(subType)) {

            assignableCheckFailed(superType, subType, message);

        }



    }



    public static void isAssignable(Class<?> superType, @Nullable Class<?> subType, Supplier<String> messageSupplier) {

        notNull(superType, (String)"Super type to check against must not be null");

        if (subType == null || !superType.isAssignableFrom(subType)) {

            assignableCheckFailed(superType, subType, nullSafeGet(messageSupplier));

        }



    }



    public static void isAssignable(Class<?> superType, Class<?> subType) {

        isAssignable(superType, subType, "");

    }



    private static void instanceCheckFailed(Class<?> type, @Nullable Object obj, @Nullable String msg) {

        String className = obj != null ? obj.getClass().getName() : "null";

        String result = "";

        boolean defaultMessage = true;

        if (StringUtils.hasLength(msg)) {

            if (endsWithSeparator(msg)) {

                result = msg + " ";

            } else {

                result = messageWithTypeName(msg, className);

                defaultMessage = false;

            }

        }



        if (defaultMessage) {

            result = result + "Object of class [" + className + "] must be an instance of " + type;

        }



        throw new IllegalArgumentException(result);

    }



    private static void assignableCheckFailed(Class<?> superType, @Nullable Class<?> subType, @Nullable String msg) {

        String result = "";

        boolean defaultMessage = true;

        if (StringUtils.hasLength(msg)) {

            if (endsWithSeparator(msg)) {

                result = msg + " ";

            } else {

                result = messageWithTypeName(msg, subType);

                defaultMessage = false;

            }

        }



        if (defaultMessage) {

            result = result + subType + " is not assignable to " + superType;

        }



        throw new IllegalArgumentException(result);

    }



    private static boolean endsWithSeparator(String msg) {

        return msg.endsWith(":") || msg.endsWith(";") || msg.endsWith(",") || msg.endsWith(".");

    }



    private static String messageWithTypeName(String msg, @Nullable Object typeName) {

        return msg + (msg.endsWith(" ") ? "" : ": ") + typeName;

    }



    @Nullable

    private static String nullSafeGet(@Nullable Supplier<String> messageSupplier) {

        return messageSupplier != null ? (String)messageSupplier.get() : null;

    }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AssertSpring 框架提供的一个断言工具类,用于在程序运行中进行断言判断,如果断言条件不满足,则会抛出异常。但是 Spring Assert 只提供了一些基本的断言方法,如果我们需要进行更加个性化的断言判断,可以通过自定义异常来实现。 自定义异常可以继承自 Spring 的 AbstractThrowableAssert 类,并重写其 fail 方法。在自定义异常中,我们可以根据需求定义不同的异常类型,例如业务异常、参数异常等,并在 fail 方法中指定不同的异常信息。 下面以一个示例来说明如何使用和自定义 Spring Assert 异常: ```java public class CustomAssert extends AbstractThrowableAssert<CustomAssert, Object> { private CustomAssert(Object actual, Class<?> selfType) { super(actual, selfType); } public static CustomAssert assertThat(Object actual) { return new CustomAssert(actual, CustomAssert.class); } public CustomAssert isPositiveNumber() { isNotNull(); if (!(actual instanceof Number) || ((Number) actual).doubleValue() <= 0) { failWithMessage("Expected positive number, but found: %s", actual); } return this; } } ``` 在自定义的 CustomAssert 类中,我们通过继承 AbstractThrowableAssert 类,并实现自己的断言方法 isPositiveNumber。在该方法中,我们首先调用 isNotNull 方法来判断输入值是否为空,然后再进行我们的特定判断,如果判断不成立,就通过 failWithMessage 方法抛出异常。 通过自定义异常,我们可以根据业务需求实现更加具体化的断言功能,并在断言失败时提供更加详细的异常信息。在使用自定义断言时,只需要调用 assertThat 方法来创建 CustomAssert 对象,并链式调用不同的断言方法即可。 总的来说,Spring Assert 的自定义异常能够帮助我们实现更加灵活和个性化的断言判断,提高代码的可读性和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值