Conditional Java compilation

Seva Alekseyev picture Seva Alekseyev · Dec 17, 2009 · Viewed 17.1k times · Source

I'm a longtime C++ programmer, new to Java. I'm developing a Java Blackberry project in Eclipse. Question - is there a way to introduce different configuration sets within the project and then compile slightly different code based on those?

In Visual Studio, we have project configurations and #ifdef; I know there's no #ifdef in Java, but maybe something on file level?

Answer

monojohnny picture monojohnny · Dec 17, 2009

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.]