Enabling and Disabling Assertions

The compiler records assertions in the classfile. However, assertions are disabled at runtime because they can affect performance. An assertion might call a method that takes awhile to complete, and this would impact the running application's performance.

You must enable the classfile's assertions before you can test assumptions about the behaviors of your classes. Accomplish this task by specifying the -enableassertions or -ea command-line option when running the java application launcher tool.

The -enableassertions and -ea command-line options let you enable assertions at various granularities based upon one of the following arguments (except for the noargument scenario, you must use a colon to separate the option from its argument):

■ No argument: Assertions are enabled in all classes except system classes.

■ PackageName...: Assertions are enabled in the specified package and its subpackages by specifying the package name followed by____

■ ...: Assertions are enabled in the unnamed package, which happens to be whatever directory is current.

■ ClassName: Assertions are enabled in the named class by specifying the class name.

For example, you can enable all assertions except system assertions when running the MergeArrays application via java -ea MergeArrays. Also, you could enable any assertions in Chapter 4's logging package by specifying java -ea:logging TestLogger.

Assertions can be disabled, and also at various granularities, by specifying either of the -disableassertions or -da command-line options. These options take the same arguments as -enableassertions and -ea. For example, java -ea -da:loneclass mainclass enables all assertions except for those in loneclass. (loneclass and mainclass are placeholders for the actual classes that you specify.)

The previous options apply to all classloaders. Except when taking no arguments, they also apply to system classes. This exception simplifies the enabling of assertion statements in all classes except for system classes, which is often desirable.

To enable system assertions, specify either -enablesystemassertions or -esa; for example, java -esa -ea:logging TestLogger. Specify either -disablesystemassertions or -dsa to disable system assertions.

Was this article helpful?

0 0

Post a comment