You can make use of the fact that if (constant)
is optimized by the compiler.
Make a global variable somewhere called DEBUG
:
public static final boolean DEBUG = true;
and then do your logging like so:
if (DEBUG) {
System.out.println("Debug");
}
To disable debugging, simply change DEBUG
to false
, and all of the logging statements will be optimized away by the compiler. You can verify this by looking at the generated bytecode with javap -c
.
For example:
class DebugTest {
public static final boolean DEBUG = true;
public static void main(String[] args) {
if (DEBUG) {
int a = 10;
System.out.println("a = " + a);
}
}
}
is compiled as:
Compiled from "DebugTest.java"
class DebugTest extends java.lang.Object{
public static final boolean DEBUG;
DebugTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: bipush 10
2: istore_1
3: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
6: new #3; //class java/lang/StringBuilder
9: dup
10: invokespecial #4; //Method java/lang/StringBuilder."":()V
13: ldc #5; //String a =
15: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: iload_1
19: invokevirtual #7; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: return
}
Changing DEBUG
to false
yields:
Compiled from "DebugTest.java"
class DebugTest extends java.lang.Object{
public static final boolean DEBUG;
DebugTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
public static void main(java.lang.String[]);
Code:
0: return
}