Saturday, February 5, 2011

Enabling assertions in eclipse projects(to a single one or all of them)

If you want to use java 1.4 assertions in java code ,you need to do these,
1.Compile using javac -source 1.4 YourCode.java .This enables assertions .Default flag is 5 .If -source flag is omitted ,compiler defaults to version 5 behavior.
2. run with java -ea YourCode

In eclipse ,you can enable assertions either for all projects or for a particular project.

Enabling assertions for all eclipse projects:
Windows-->Preferences-->Java-->Installed JREs
Select one of the listed JREs (eg:java-6-sun-1.6.0.20)
click Edit.
In the textfield labelled Default VM Arguments add -ea
click Finish.

Now if you put an assert statement in any of your projects ,it will be executed

Enabling assertions for a particular run configuration:
Select the particular project and get Properties(or click Alt+Enter).
Select Run/Debug settings
From the listed launch configurations select the one you need to enable assertions for.
Click Edit.
Select the Arguments tab.
In VM Arguments textbox add -ea

Now the assert statements in this project will be executed.

an an aside,check out google's contracts for java blog
and http://code.google.com/p/cofoja/