If I have a boolean field like:
private static final boolean DEBUG = false;
and within my code I have statements like:
if(DEBUG) System.err.println("err1");
does the Java preprocessor just get rid of the if statement and the unreachable code?
A preprocessor is a program that works on the source before the compilation. As the name implies, the preprocessor prepares the source for compilation. The notion of the preprocessor has been there from the earliest times of programming languages.
Source code written in Java is simple. There is no preprocessor, no #define and related capabilities, no typedef , and absent those features, no longer any need for header files. Instead of header files, Java language source files provide the declarations of other classes and their methods.
Java doesn't have a preprocessor - so the simple answer is that you can't. This sort of thing is normally handled in Java using Dependency Injection - which is both more powerful and more flexible.
In computer science, a preprocessor (or precompiler) is a program that processes its input data to produce output that is used as input to another program. The output is said to be a preprocessed form of the input data, which is often used by some subsequent programs like compilers.
Most compilers will eliminate the statement. For example:
public class Test { private static final boolean DEBUG = false; public static void main(String... args) { if (DEBUG) { System.out.println("Here I am"); } } }
After compiling this class, I then print a listing of the produced instructions via the javap
command:
javap -c Test Compiled from "Test.java" public class Test extends java.lang.Object{ public Test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: return public static void main(java.lang.String[]); Code: 0: return }
As you can see, no System.out.println
! :)
Yes, the Java compiler will eliminate the compiled code within if
blocks that are controlled by constants. This is an acceptable way to conditionally compile "debug" code that you don't want to include in a production build.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With