Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Java compilation

Tags:

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?

like image 678
Seva Alekseyev Avatar asked Dec 17 '09 15:12

Seva Alekseyev


People also ask

What is meant by conditional compilation?

Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.

What statements are used for conditional compilation?

The $ELSE statement is used in conjunction with the $IF statement to control conditional compilation. The $END statement is used in conjunction with the $IF statement to control conditional compilation. A $IF statement provides the means whereby selected parts of the source text are not included in the compilation.

Does Java have Ifdef?

Java does not include any kind of preprocessor like the C cpp preprocessor. It may seem hard to imagine programming without #define, #include, and #ifdef, but in fact, Java really does not require these constructs.

What is conditional compilation in C?

Conditional compilation is the process of selecting which code to compile and which code to not compile similar to the #if / #else / #endif in C and C++. Any statement that is not compiled in still must be syntactically correct. Conditional compilation involves condition checks that are evaluable at compile time.


2 Answers

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

like image 58
4 revs Avatar answered Oct 26 '22 00:10

4 revs


you can manage different classpath, for example, implement each 'Action' in a set of distinct directories:

dir1/Main.java
dir2/Action.java
dir3/Action.java

then use a different classpath for each version

javac -sourcepath dir1 -cp dir2 dir1/Main.java

or

javac -sourcepath dir1 -cp dir3 dir1/Main.java
like image 36
Pierre Avatar answered Oct 26 '22 00:10

Pierre