java 断言给出了奇怪的结果

发布于 2024-07-27 18:03:54 字数 229 浏览 2 评论 0原文

下面的java代码应该做什么?

public class foo{
    public static void main(String[] args){
        boolean mybool=false;
        assert (mybool==true);
    }
}

这应该引发断言错误吗? 如果不,为什么不呢? (我没有收到任何错误!)

what should the following java code do?

public class foo{
    public static void main(String[] args){
        boolean mybool=false;
        assert (mybool==true);
    }
}

Should this throw an assertion error? and if not why not? (I'm not getting any errors!)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

木槿暧夏七纪年 2024-08-03 18:03:55

运行程序时,您必须通过在命令行中添加“-ea”来在 Java VM 中启用断言:

java -ea -jar myprogram.jar

When running the program, you have to enable assertions in the Java VM by adding '-ea' to the command line:

java -ea -jar myprogram.jar
新人笑 2024-08-03 18:03:55

Java 语言的断言很奇怪。 您必须在启动命令行时启用它们,我不喜欢这样。

因此,我倾向于使用第三方库来进行断言。 Apache Commons Lang(通过 Validator 类)、Spring(通过 Assert 类)甚至 JUnit4(通过 Assert 类)都提供此功能,并且无论 VM 设置如何,它都可以工作。 当您使用 Java5 静态导入时,它们与 java 断言一样易于使用,而且它们更加灵活,而且它们允许您在异常中指定错误消息。

Java-language assertions are weird. You have to enable them when you launch the command line, and I don't like that.

For this reason, I tend to use 3rd-party libraries to do my assertions. Apache Commons Lang (via the Validator class), Spring (Via the Assert class) or even JUnit4 (via the Assert class) all provide this functionality, and it'll work regardless of VM settings. When you use Java5 static imports, they're just as easy to use as java assert, plus they're more flexible, plus they allow you to specify the error message in the exception.

呆橘 2024-08-03 18:03:55

这应该抛出AssertionErors

如果您使用 Eclipse,则需要打开断言。 默认情况下它们被禁用。

为此,请将 -ea 添加到 JVM 参数中。

This should be throwing AssertionErors.

You need to turn on assertions if you are using Eclipse. It has them disabled by default.

To do this, add -ea to the JVM arguments.

爱给你人给你 2024-08-03 18:03:55

这使得可以在程序中访问是否启用断言的信息。

如果禁用断言(这是默认设置),则断言语句将不会被执行,并且 mybool 的值为 false。

如果启用断言(jvm 参数 -ea),则断言将被执行,并且产生副作用 mybool 将被设置为 true。

您可以使用它来强制启用或禁用断言。 例如,我的 TestSuites 中有一个测试,如果未启用断言,该测试就会失败,以便强制断言在运行测试时始终处于打开状态。

This makes the information if Assertions are enabled accessible in the program.

If assertions are disabled (this is the default) the assertion statement will not be executet, and mybool will have the value false.

if assertions are enabled (jvm argument -ea) the assertion will get executed, and by a side effect mybool will be set to true.

You can use that to enforce enabling or disabling of assertions. For example I have a Test in my TestSuites that failes if assertions are not enabled, in order to enforce that the assertions are always on when running the tests.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文