devxlogo

Preprocessor Support

Preprocessor Support

Question:
Is there something similar to the C/C++ compiler directive #ifdef,#define, and #endif in Java? I would like to compiledebugging code conditionally.

Answer:
This is one of the first questions that crossed my mind when I firststarted programming in Java. The disappointing answer is no. Noteveryone agrees on the need for Java to include flexibleconditional compilation support or some of the other beneficialfeatures provided by a preprocessor.

Nonetheless, there are severalrather compelling reasons for using a preprocessor beyondconditionally compiling debugging code. The most compelling reasonthat developers are facing on an increasing basis is the need tomaintain different versions of classes from the same source file. Aprime example of this today is when you need to support a classlibrary for both Java 2 Standard Edition and Java 2 Micro Edition.When all you have to do is remove import java.io.* and make a classnot implement java.io.Serializable to make it work for J2ME,conditional compilation is just the right thing. Even though thereare alternative ways of approaching the problem, they typically resultin code bloat.

For the case of maintaining debugging code, a widely suggestedapproach is to declare a static final Boolean constant, initializingit to True when you want to turn debugging on and to False when youwant it off. Then place debugging code inside an If statement thattests the value of the constant. This allows the compiler to optimizeout all debugging code when the constant’s value is equal to False.This approach is inadequate for solving the general problem ofconditional compilation, but it will allow you to conditionallyinclude debugging code.

You may want to search the Web for one ofseveral preprocessor implementations for Java, but keep in mind thatnone of them is standard.

devx-admin

Share the Post: