为什么“断言是虚假的"?以编程方式激活断言时不会导致AssertionError吗? [英] Why is "assert false" not causing AssertionError when assertion are activated programmatically?

查看:116
本文介绍了为什么“断言是虚假的"?以编程方式激活断言时不会导致AssertionError吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Oracle文档

ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
ClassLoader.getSystemClassLoader().setPackageAssertionStatus("richtercloud.java.assertion.ignored", true);
System.out.println(String.format("desired assertion status: %b",
        NewMain.class.desiredAssertionStatus()));
assert false;
System.out.println("assertion has been ignored");

在类richtercloud.java.assertion.ignored.NewMainmain方法中的

,我从打印的语句中看到assert false不会导致AssertionError,就像我将NewMain打包在JAR中并使用java -ea -jar java-assertion-ignored-1.0-SNAPSHOT-jar-with-dependencies.jar richtercloud.java.assertion.ignored.NewMain.

in the main method of a class richtercloud.java.assertion.ignored.NewMain, I see from the printed statement that assert false doesn't cause an AssertionError like it's caused if I package NewMain in a JAR and run it with java -ea -jar java-assertion-ignored-1.0-SNAPSHOT-jar-with-dependencies.jar richtercloud.java.assertion.ignored.NewMain.

关于以编程方式启用断言的其他问题仅建议不使用断言显然不是解决方案.

Other questions regarding programmatic enabling of assertion only suggest to not use assertions which is obviously not a solution.

MCVE,位于 https://github.com/krichter722/java-assertion-ignored.

推荐答案

如果我正确地理解了文档,则必须在加载类之前设置断言状态;否则,请参见图5.在此示例中,您已经加载了该类,因此您的setDefaultAssertionStatus(true)没有任何作用.

If I'm understanding the documentation correctly, you have to set assertion status before loading the class; in this example you have already loaded the class, so your setDefaultAssertionStatus(true) has no effect.

从文档中引用(我的斜体字):

每个类加载器都维护一个默认断言状态,该布尔值确定默认情况下在由随后初始化的新类中启用或禁用断言.类加载器.

Each class loader maintains a default assertion status, a boolean value that determines whether assertions are, by default, enabled or disabled in new classes that are subsequently initialized by the class loader.

因此,设置默认的断言状态只会影响随后加载的类,而不会影响当前正在执行的类.

Therefore, setting the default assertion status will only affect subsequently-loaded classes, not the currently executing one.

这篇关于为什么“断言是虚假的"?以编程方式激活断言时不会导致AssertionError吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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