Java assert 关键字有什么作用,应该在什么时候使用? [英] What does the Java assert keyword do, and when should it be used?

查看:36
本文介绍了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;
}

这篇关于Java assert 关键字有什么作用,应该在什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆