spring中的Assert工具类的使用(如何写出优雅的代码)

Assert常用于数据合法性校验,不通过就报异常,常规写法

if (text != null && "".equals(text)) {
    
    
            throw new IllegalArgumentException("字符不能为null,且至少包含一个非空格字符");
        }

用Assert工具类就可以这样替代

Assert.hasText(text,"字符不能为null,且至少包含一个非空格字符"); //String

常用Assert介绍

public class testAssert {
    
    
    public static void main(String[] args) {
    
    
        String text = "";
        Object object = null;
        Boolean btext = false;
        ArrayList<Integer> list = new ArrayList<>();
        if (text != null && "".equals(text)) {
    
    
            throw new IllegalArgumentException("字符不能为null,且至少包含一个非空格字符");
        }
        //list.add(1);
        //Assert.hasText(text,"字符不能为null,且至少包含一个非空格字符"); //String
        //Assert.hasLength(text,"字符不能为null,且字符长度不为0"); //String
        //Assert.notEmpty(list,"集合不能为空");
        //Assert.notNull(object,"对象不能为null"); //Object
        //Assert.isTrue(btext,"对象必须为true"); //布尔类型
        Assert.isInstanceOf(Object.class, new Goods(), "不能转换成Goods类型");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42875345/article/details/113394075