是否有与Kotlin的require函数等效的内置Java?
Kotlin 有一个require函数,可以像这样使用(从参考文档中复制):
fun getIndices(count: Int): List<Int> {
require(count >= 0) { "Count must be non-negative, was $count" }
// ...
return List(count) { it + 1 }
}
// getIndices(-1) // will fail with IllegalArgumentException
println(getIndices(3)) // [1, 2, 3]
如果值为 false,该函数本质上会抛出 IllegalArgumentException。显然,这可以很容易地在 Java 中实现 - 但我想知道 JDK 或 apache 库(或任何其他无处不在的库)中是否已经有一些东西提供了这样的功能?
回答
您可以使用assert与 Kotlinrequire方法等效的函数。
assert count >= 0 : "Count must be non-negative, was " + count;
使用断言编程
JDK 默认禁用断言操作。如果要启用断言操作,则必须使用 VM 选项定义启用的包或类位置,例如-ea:com.example.demo...
启用和禁用断言
我更喜欢 Spring Framework 的org.springframework.util.Assert类,因为有很多验证参数的方法。
更简单的方法:
Assert.isTrue(count >= 0, "Count must be non-negative, was " + count);
懒惰的方式(为了更好的性能和与 kotlinrequire函数相同的流程):
Assert.isTrue(count >= 0, () -> "Count must be non-negative, was " + count);
Spring 断言语句
对于单元测试,您可以使用 Junit ( org.junit.Assert) 或 Jupiter ( org.junit.jupiter.api.Assertions) 断言函数。
- One disadvantage of a normal function like the Junit or Spring ones is that they always construct the message string even if the assertion passes; in high-performance systems, the extra temporary objects could have a significant impact. (That's why the Kotlin function takes a lambda, of course.)