Conditional Java compilation

You can set up ‘final’ fields and ifs to get the compiler to optimize the compiled byte-codes.

...
public static final boolean myFinalVar=false;
...
if (myFinalVar) { 
 do something ....
 ....
}

If ‘myFinalVar’ is false when the code is compiled the ‘do something….’ bit will be missed out of the compiled class. If you have more than one condition – this can be tidied up a bit: shift them all to another class (say ‘Config.myFinalVar’) and then the conditions can all be kept in one neat place.

This mechanism is described in ‘Hardcore Java’.

[Actually I think this is the same mechanism as the “poor man’s ifdef” posted earlier.]

Leave a Comment