Using Java compiler as preprocessor
February 1, 2007 · Programming
I asked him to take a look to some Java preprocessor implementation that are available freely on the internet, and also pointed him to use log4j or another logging facility.
I also had a second thought, a way to use the compiler's optimization process to benefit you with these kind of problems. Consider the following code:
public class Test {
private static final boolean DEBUG = false;
public static void main(String[] args) {
if(DEBUG) {
System.out.println("debug is on");
}
}
}
We set the DEBUG class attribute as false or true, when we want to enable ... disable the debug information.
The disassembled code with debug (DEBUG = true) is listed below:
nefarian:~ bkarak$ javap -c Test
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: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3; //String debug is on
5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
}
and without (DEBUG = false):
nefarian:~ bkarak$ javap -c Test
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
}
The Java compiler deletes this code because it is considered unreachable statement. Nice isn't it? :)