Friday, 21 January 2011

Using Java Assert

The idea of asserts was introduced to Java as part of the language in J2SE 1.4.

To allow the compiler to treat "assert" as a keyword you'll need to compile with the following amendment to the compile line:

javac -source 1.4

To enable the assertion at runtime use the following command line option:

java -ea MyApp


java -ea:<packagename> MyApp

The format of an assert statement is:

    assert expression1: expression2;

Expression1 is a boolean used to trigger the assert..
Expression2 is passed to the constructor of the AssertionError object that deals with the assert problem. Expression2 is optional.

  public class AssertDemo {
public static void main(String[] args) {
assert args.length != 0: "We don't take parameters!";

And finally... remember to add -source 1.4 (or greater) to the javadoc command line so that it recognises the assert keyword.

No comments: