Java —— 断言(以Spring的Assert为例)

问题

Java中的断言适合什么场景?如何使用?

解决

当断言的条件为假的时候,程序会抛出异常,终止当前任务的执行。当这个关键字后面的条件为真的时候,程序继续执行下一句语句。

示例(以Spring的Assert为例)

    import org.springframework.util.Assert;

	public void test(String a) {
		Assert.notNull(a,"字符串a为空 :(");
	}

方法汇总

Assert.notNull(Object object,"object is required"); 对象非空
Assert.isTrue(Object object,"object must be true"); 对象必须为true
Assert.notEmpty(Collection collection,"collection must not be empty"); 集合不能为空
Assert.hasLength(String text,"text must be specified"); 字符不为null且字符长度不为0
Assert.hasText(String text,"text must not be empty"); text不为null且必须至少包含一个非空的字符
Assert.isInstanceOf(Class class, Object object,"class must be of type[class]"); object必须为class指定的类

注意

断言可能会被设置为只在本地与测试环境有效,生产环境也许会失效。具体项目具体分析。

猜你喜欢

转载自blog.csdn.net/xue_xiaofei/article/details/113994366