问题
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