One of the correct answers from OCP Java SE 6 Programmer Practice Exams is:
You can programmatically test wheather assertions have been enabled without throwing an
AssertionError
.
How can I do that?
I use this
boolean assertOn = false;
// *assigns* true if assertions are on.
assert assertOn = true;
I am not sure this is the "official" way.
I guess you should use Class.desiredAssertionStatus()
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#desiredAssertionStatus()
The Oracle Java Tutorial provides information about how to do it...
http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html
An excerpt from the tutorial
7. Why not provide a construct to query the assert status of the containing class?
Such a construct would encourage people to inline complex assertion code, which we view as a bad thing. Further, it is straightforward to query the assert status atop the current API, if you feel you must:
boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side-effect!!! // Now assertsEnabled is set to the correct value
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
boolean assertionsEnabled = mx.getInputArguments().contains("-ea");
package io.github.baijifeilong.tmp;
import io.vavr.control.Try;
/**
* Created by BaiJiFeiLong@gmail.com at 2019-04-18 09:12
*/
public class TmpApp {
public static void main(String[] args) {
Try.run(() -> {
assert false;
}).onSuccess($ -> {
throw new RuntimeException("Assertion is not enabled");
});
}
}
Maybe help someone.
来源:https://stackoverflow.com/questions/13029915/how-to-programmatically-test-if-assertions-are-enabled