编程语言
首页 > 编程语言> > java-为什么以编程方式激活断言时“断言为假”不会引起AssertionError?

java-为什么以编程方式激活断言时“断言为假”不会引起AssertionError?

作者:互联网

如果我在Oracle documentation之后激活断言

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.NewMain的主要方法中,我从打印的语句中看到断言false不会导致AssertionError,就像我将NewMain打包在JAR中并使用java -ea-运行它时那样jar java-assertion-ignored-1.0-SNAPSHOT-jar-with-dependencies.jar richtercloud.java.assertion.ignored.NewMain.

关于以编程方式启用断言only suggest to not use assertions的其他问题显然不是解决方案.

MCVE在https://github.com/krichter722/java-assertion-ignored.

解决方法:

如果我正确地理解了文档,则必须在加载类之前设置断言状态.在此示例中,您已经加载了该类,因此setDefaultAssertionStatus(true)无效.

Quoting from the documentation(斜体字):

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.

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

标签:assertions,java
来源: https://codeday.me/bug/20191026/1932874.html