为什么像springsecurity这样的spring-boot库在/src/main中有断言,而没有为此类验证抛出异常



当我浏览spring引导存储库中的许多模块时,我可以在/src/main/中找到断言,如下所示

public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
Set<String> scopes) {
super(tokenValue, issuedAt, expiresAt);
Assert.notNull(tokenType, "tokenType cannot be null");
this.tokenType = tokenType;
this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
}

不是应该使用异常来代替/src/main/下的所有此类验证吗。

据我所读,断言是指用于/src/test/下的测试用例。

确实引发异常。单词";断言";简单地表示";声明某事应该是真的";,这可能发生在测试或运行时。您正在将断言的概念与Java中assert关键字的特定工具或测试断言库(如AssertJ(合并。

在这种特殊情况下,所讨论的Assertorg.springframework.util.Assert:

/**
* Assert that an object is not {@code null}.
* <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
* @param object the object to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object is {@code null}
*/
public static void notNull(@Nullable Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}

GuavaPreconditions和commons langValidate也提供类似的设施;它们不被称为";断言";,但它们具有相同的语义。

最新更新