public final class Assert
extends java.lang.Object
11.6 How can I write C/C++ style assertions in Java? A. The two classes shown below provide an assertion facility in Java. Set Assert.enabled to true to enable the assertions, and to false to disable assertions in production code. The AssertionException is not meant to be caught--instead, let it print a trace. With a good optimizing compiler there will be no run time overhead for many uses of these assertions when Assert.enabled is set to false. However, if the condition in the assertion may have side effects, the condition code cannot be optimized away. For example, in the assertionAssert.assertExp(size() <= maxSize, "Maximum size exceeded");
the call to size() cannot be optimized away unless the compiler can see that the call has no side effects. C and C++ use the preprocessor to guarantee that assertions will never cause overhead in production code. Without a preprocessor, it seems the best we can do in Java is to writeAssert.assertExp(Assert.enabled && size() <= maxSize, "Too big");
In this case, when Assert.enabled is false, the method call can always be optimized away, even if it has side effects.
Modifier and Type | Field and Description |
---|---|
static boolean |
enabled
Globally enable or disable assertions.
|
public static final boolean enabled
public static final void assertExp(boolean b, java.lang.String s)
b
- An expression expected to be trues
- Exception string if expression is falseAssertionException
- if expression is falsepublic static final void assertExp(boolean b)
b
- An expression expected to be trueAssertionException
- if expression is falseCopyright (C) BBNT Solutions LLC; See http://openmap.bbn.com/ for details