In c\c++ can define:
#ifndef <token>
/* code */
#else
/* code to include if the token is defined */
#endif
my question, is there a way to do it in java? (which is not defining a global static variable..)
for example i want to run some code only in debug mode..
thanks!
The answer is No. Not in the sense that you mean.
The way you do this kind of thing in Java as follows:
Java doesn’t have a preprocessor (like C and C++ do). However, the compiler will optimize away the unused branch of an
ifstatement like the above, PROVIDED thatflagis a compile-time constant expression. This is a limited form of conditional compilation. Note that the controllingflagconstant can be imported from a different class.(IIRC, this behaviour is specified in the JLS … which means that you can rely on any conforming Java compiler to do it.)
@Treebranch comments that “this” can cause code bloat.
If @Treebranch is talking about object code bloat, this is not true. If you do this right with flags/expressions that are compile-time constant expressions as defined by the JLS, then the compiler does not emit any bytecodes for the “conditionally excluded” source code. See @edalorso’s answer.
If @Treebranch is are talking about source-code bloat, I agree. But you can say the same thing for
#ifdefconditional compilation. (Macros and#includecan be used to reduce source-code bloat … but only at the cost of readability, maintainability, etc. And that was the reason that the Java designers refused to support any source-code preprocessing.)Java has a better way of dealing with platform differences, functionality variations and so on: use dynamic binding. If having lots of different plugin classes in your JAR is a concern (bytecode bloat), deal with it by creating a different JAR file for each platform, or whatever.