Java教程

Java中Spring的Assert断言的使用

本文主要是介绍Java中Spring的Assert断言的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java中Spring的Assert断言的使用

  • 1 Spring的Assert的简介
  • 2 Spring的Assert的使用

Java中Assert的使用日常较少, 使用Assert可以提高代码的可读性,但过度使用,会导致不利于后期代码的维护.

1 Spring的Assert的简介

Java中断言assert是一个关键字, 主要是验证某些条件是否成立. 在一些编辑器中,需要开启assert断言功能,才可以使用,如IDEA,Eclipse等 ,很不方便使用,在生产等环境不适用, 故常常使用的是Spring框架封装的org.springframework.util.Assert断言.

部分源代码:

public abstract class Assert {

	/**
	 * Assert a boolean expression, throwing an {@code IllegalStateException}
	 * if the expression evaluates to {@code false}.
	 * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
	 * on an assertion failure.
	 * <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre>
	 * @param expression a boolean expression
	 * @param message the exception message to use if the assertion fails
	 * @throws IllegalStateException if {@code expression} is {@code false}
	 */
	public static void state(boolean expression, String message) {
		if (!expression) {
			throw new IllegalStateException(message);
		}
	}

	/**
	 * Assert a boolean expression, throwing an {@code IllegalStateException}
	 * if the expression evaluates to {@code false}.
	 * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
	 * on an assertion failure.
	 * <pre class="code">
	 * Assert.state(entity.getId() == null,
	 *     () -&gt; "ID for entity " + entity.getName() + " must not already be initialized");
	 * </pre>
	 * @param expression a boolean expression
	 * @param messageSupplier a supplier for the exception message to use if the
	 * assertion fails
	 * @throws IllegalStateException if {@code expression} is {@code false}
	 * @since 5.0
	 */
	public static void state(boolean expression, Supplier<String> messageSupplier) {
		if (!expression) {
			throw new IllegalStateException(nullSafeGet(messageSupplier));
		}
	}

	/**
	 * Assert a boolean expression, throwing an {@code IllegalStateException}
	 * if the expression evaluates to {@code false}.
	 * @deprecated as of 4.3.7, in favor of {@link #state(boolean, String)}
	 */
	@Deprecated
	public static void state(boolean expression) {
		state(expression, "[Assertion failed] - this state invariant must be true");
	}

	/**
	 * Assert a boolean expression, throwing an {@code IllegalArgumentException}
	 * if the expression evaluates to {@code false}.
	 * <pre class="code">Assert.isTrue(i &gt; 0, "The value must be greater than zero");</pre>
	 * @param expression a boolean expression
	 * @param message the exception message to use if the assertion fails
	 * @throws IllegalArgumentException if {@code expression} is {@code false}
	 */
	public static void isTrue(boolean expression, String message) {
		if (!expression) {
			throw new IllegalArgumentException(message);
		}
	}

	/**
	 * Assert a boolean expression, throwing an {@code IllegalArgumentException}
	 * if the expression evaluates to {@code false}.
	 * <pre class="code">
	 * Assert.isTrue(i &gt; 0, () -&gt; "The value '" + i + "' must be greater than zero");
	 * </pre>
	 * @param expression a boolean expression
	 * @param messageSupplier a supplier for the exception message to use if the
	 * assertion fails
	 * @throws IllegalArgumentException if {@code expression} is {@code false}
	 * @since 5.0
	 */
	public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
		if (!expression) {
			throw new IllegalArgumentException(nullSafeGet(messageSupplier));
		}
	}

	/**
	 * Assert a boolean expression, throwing an {@code IllegalArgumentException}
	 * if the expression evaluates to {@code false}.
	 * @deprecated as of 4.3.7, in favor of {@link #isTrue(boolean, String)}
	 */
	@Deprecated
	public static void isTrue(boolean expression) {
		isTrue(expression, "[Assertion failed] - this expression must be true");
	}
} 

从代码可知,Assert断言的表达式基本分为两类

  • Assert.方法名 (布尔表达式) : 这类方法都标记过时, 都调用第二类方法
  • Assert.方法名 (布尔表达式,错误提示信息) : 这类方法, 如果布尔表达式不满足,会抛出异常,并将异常信息封装.

在使用方法时不满足布尔表达式, 就会抛出相应的异常,如IllegalStateException和IllegalArgumentException, 此类异常都属于运行时异常.

2 Spring的Assert的使用

        if (条件为真) {
            // 业务处理
        }

上述可替换成

Assert.isTrue(条件为真, "条件不满足");
// 业务处理
    public static void main(String[] args) {

        Assert.isTrue(1>0);
        System.out.println("断言 1>0 成功");
        Assert.isTrue(1 < 0, "断言1 < 0失败");
    }


/*
	运行结果:
	Exception in thread "main" 断言 1>0 成功
java.lang.IllegalArgumentException: 断言1 < 0失败
	at org.springframework.util.Assert.isTrue(Assert.java:121)
	at com.cf.demo.config.MailTest2.main(MailTest2.java:61)

*/

使用时发现,Spring中主要抛出非法参数异常和非法状态异常, 主要用来做参数的校验,可以提高代码的可读性.对于一些说法, 关于可以替代if-else语句, 是不合理的. if-else主要用来做条件分支判断,满足那个就进入那个, 而Assert断言,满足条件才会向下运行,不满足,直接抛出异常,二者应用场景不一致.

参考资料:

https://www.runoob.com/w3cnote/c-assert.html

https://zhuanlan.zhihu.com/p/265444322

这篇关于Java中Spring的Assert断言的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!