Java断言关键字做了什么,何时应该使用它? [英] What does the Java assert keyword do, and when should it be used?

查看:152
本文介绍了Java断言关键字做了什么,何时应该使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是现实生活中的例子来理解断言的关键作用?

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

推荐答案

< a href =http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.10 =noreferrer>断言(通过在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断言关键字做了什么,何时应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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