Why is “assert false” not causing AssertionError when assertion are activated programmatically?

有些话、适合烂在心里 提交于 2019-12-10 21:09:46

问题


If I activate assertions following the 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");

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 at https://github.com/krichter722/java-assertion-ignored.


回答1:


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.

Quoting from the documentation (my italics):

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.



来源:https://stackoverflow.com/questions/44123763/why-is-assert-false-not-causing-assertionerror-when-assertion-are-activated-pr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!