Karl Richter Karl Richter - 1 year ago 46
Java Question

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

If I activate assertions following the Oracle documentation

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

in the
method of a class
, I see from the printed statement that
assert false
doesn't cause an
like it's caused if I package
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download