Home > Java > How to turn on assertions in a JAR?

How to turn on assertions in a JAR?

April 18th, 2008

We have told you that it is not possible to turn on assertions in a Jar. That is not quite true, there is a Java compiler plugin that forces assertions to be turned on, independent of the VM’s -ea setting.

To make sure that assertion are always checked, simply include fa.jar into the classpath when compiling your source. FA will automagically turn all your assert statements into if-not-condition-throw-error expressions that can not the turned off!

Bending JSR 269 beyond its limits, I’ve written a small annotation processor (ie javac plugin) that replaces assertions statements with an explicit throw expression. Each assert statement

assert cond : detail;

is replaced with

if (!cond) throw new Assertion(detail);

The latter does not generate an assert bytecode and hence your assertions are checked even when your client’s VM runs without assertions enabled. This is most useful for libraries, where you have no control over your client’s VM settings.

To use this processor simply include fa.jar in the classpath when running javac, the discovery process will automagically discover the processor. If the processor has been applied, javac will print a note of the form

Note: %n assertions inlined.

If you want to double-check what fa.jar does, you might want to use javac’s hidden -printsource option to inspect the source code of the modified compilation units.

Download

http://forceassertions.googlecode.com

Note fa.jar requires javac 1.6 to run properly, it does not work under javac 1.5 or Eclipse’s compiler!

admin Java

Comments are closed.