Java assert 关键字有什么作用,应该在什么时候使用?

Java assert 关键字有什么作用,应该在什么时候使用?

问题描述:

有哪些现实生活中的例子可以理解断言的关键作用?

What are some real life examples to understand the key role of assertions?

断言(通过assert 关键字)是在Java 1.4 中添加的.它们用于验证代码中不变量的正确性.它们永远不应该在生产代码中被触发,并且表示代码路径存在错误或误用.它们可以在运行时通过 java 命令中的 -ea 选项激活,但默认情况下不会打开.

Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the -ea option on the java command, but are not turned on by default.

示例:

public Foo acquireFoo(int id) {
  Foo result = null;
  if (id > 50) {
    result = fooService.read(id);
  } else {
    result = new Foo(id);
  }
  assert result != null;

  return result;
}