Java中的断言关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3806173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 05:19:48  来源:igfitidea点击:

Assert keyword in Java

javavalidationexceptionassert

提问by Stan Kurilin

Do you use the assertkeyword or throw some validation runtime exception? What benefits does it give to you or why do you think it's not worth it to use?

你使用assert关键字还是抛出一些验证运行时异常?它给你带来什么好处,或者你为什么认为它不值得使用?

采纳答案by andersoj

Assert will throw a runtime error (AssertionError) if its condition is false. Asserts give you a streamlined way of documenting, checking, and enforcing correctness criteria for your code. The benefits are a language-level hook for defining and manipulating these correctness conditions. To the extent that you wish to enable or disable them (there are arguments about whether or not this is a good idea) you can do so from the JVM command-line. Some commenters below note that assertions are disabled by default unless running in debug mode; my practice is to add "-ea" (enable assertions) in my wrapper scripts at all times. Even in performance sensitive code, for me the tradeoff weighs in favor of the security/correctness confidence I get from assertions. Assertions at Oracleand API Description for AssertionError

如果条件为假,断言将抛出运行时错误 ( AssertionError)。断言为您提供了一种简化的方式来记录、检查和强制执行代码的正确性标准。好处是用于定义和操作这些正确性条件的语言级挂钩。如果您希望启用或禁用它们(关于这是否是一个好主意存在争论),您可以从 JVM 命令行执行此操作。下面的一些评论者指出,除非在调试模式下运行,否则默认情况下断言是禁用的;我的做法是始终在我的包装脚本中添加“-ea”(启用断言)。即使在对性能敏感的代码中,对我来说,权衡也会有利于我从断言中获得的安全性/正确性信心。 Oracle 的断言断言错误的 API 描述

Note the distinction between expected or unexpected failures (exceptions), which may be outside your control, and assertion failures -- assertion failures document programmer assumptions, and indicate an incorrect program rather than an unexpected external condition or expected exceptional condition. If an assertion failure occurs, the interpretation is that the programmer has misunderstood or incorrectly expressed the program, rather than other sources of error or failure.

请注意可能超出您控制范围的预期或意外失败(异常)与断言失败之间的区别——断言失败记录了程序员的假设,并表明程序不正确,而不是意外的外部条件或预期的异常情况。 如果发生断言失败,则解释是程序员误解或错误地表达了程序,而不是其他错误或失败的来源。

In practice, I use it to document obvious or non-obvious assumptions I make and invariants which I want to enforce as I produce (particularly private/internal) code, making it clear to myself and others why these assumptions are made, where they are made, and whether or not they are validated. Much better than comments to the same effect. This is a (small) step toward Design by Contract.

在实践中,我用它来记录我做出的明显或不明显的假设以及我在生成(特别是私有/内部)代码时想要强制执行的不变量,让我自己和其他人清楚为什么做出这些假设,它们在哪里制作,以及它们是否经过验证。比相同效果的评论要好得多。这是朝着按合同设计的(小)步骤。

Effective Java item #38 "Check Parameters for Validity" (Google Books, Amazon.com) provides a useful presentation of the distinction between parameter checking and appropriate use of assertions.

Effective Java item #38“Check Parameters for Validity”(Google BooksAmazon.com)提供了一个有用的介绍,说明了参数检查和正确使用断言之间的区别。

Related on SO: (Enabling assertions in netbeans), (Assertions vs. Exceptions), (Near duplicate, asking for examples), (Badly named, but very similar content)

与 SO 相关:(在 netbeans 中启用断言),(断言与异常),(几乎重复,要求示例),(名称错误,但内容非常相似

回答by Plínio Pantale?o

andersoj is correct. Just for you to know, the great thing about asserts is that you can simple turn it off (if you dont pass -ea in java command line). This simple thing make them perfect for use in development, when you want to be sure you are not breaking your own code.  

andersoj 是正确的。只是让您知道,断言的好处在于您可以简单地将其关闭(如果您没有在 java 命令行中传递 -ea)。当您想确保不会破坏自己的代码时,这个简单的事情使它们非常适合在开发中使用。  

回答by irreputable

you can use it to enable something during dev, then disable it completely on live site. for example

您可以使用它在开发期间启用某些功能,然后在实时站点上完全禁用它。例如

...
assert debug("xxx");
...

static boolean debug(String format, Object... args){ print(...); return true; }

the debug statement will add zero overhead on live site.

调试语句将在实时站点上增加零开销。

回答by Balaji Boggaram Ramanarayan

To be precise on your question :

准确地说你的问题:

Assert is used to validate the condition of a statement.

断言用于验证语句的条件。

assert (some condition)
Example : assert (6 < 7) // condition pass
          assert (6 > 7) // throws AssertionException here

Most people use assert for the following use case for String : (But I personally hate to use assert for it) :

大多数人将断言用于 String 的以下用例:(但我个人讨厌使用断言):

assert (obj != null || obj.isEmpty() || ... )

I rather like using google guava which is clean and serve the purpose :

我更喜欢使用谷歌番石榴,它很干净并且可以达到目的:

Obj.isNullOrEmpty()

More info : http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html

更多信息:http: //docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Strings.html

回答by kervin

What benefits does it give to you or why you think it's not worth to use?

它给您带来什么好处,或者您认为它不值得使用的原因是什么?

Using asserts for mandatory checks, as others have recommended is a dangerous practice.

正如其他人所推荐的那样,使用断言进行强制性检查是一种危险的做法

What happens when another developer uses your library? Or a System Admin or Power User forgets, or worse doesn't know, to enable asserts with the -eaflag at runtime? You lose all these checks, that's what.

当其他开发人员使用您的库时会发生什么?或者系统管理员或高级用户忘记了,或者更糟的是不知道在运行时启用带有-ea标志的断言?你失去了所有这些支票,就是这样。

Asserts are a development tool. The fact that the flag's default state is offis a dead give-away.

断言是一种开发工具。标志的默认状态是关闭的这一事实是一个致命的放弃。

No feature or benefit in your application should ever depend on a assert being on.

您的应用程序中的任何功能或优势都不应该依赖于断言。

As background, asserts are used the same way in C/C++ where the feature was taken from. In C/C++ a developer can usually pass in a #define DEBUG ...at compile time to enable or disable asserts. With C/C++ production code usually having this feature off.

作为背景,断言在 C/C++ 中的使用方式与该功能的来源相同。在 C/C++ 中,开发人员通常可以#define DEBUG ...在编译时传入 a来启用或禁用断言。使用 C/C++ 生产代码通常会关闭此功能。

Conceptually, the same should be true for Java. In production use conditionals and Exceptions. They are essentially the same thing.

从概念上讲,Java 也应该如此。在生产中使用条件和异常。它们本质上是一回事。