Java Reference
In-Depth Information
statement should not be emitted by the compiler either. Presto—instant conditional compila-
tion!
This is shown in the following code:
// IfDef.java
final boolean DEBUG = false;
System.out.println("Hello, World ");
if (DEBUG) {
System.out.println("Life is a voyage, not a destination");
}
Compilation of this program and examination of the resulting class file reveals that the string
“Hello” does appear, but the conditionally printed epigram does not. The entire println has
been omitted from the class file. So Java does have its own conditional compilation mechan-
ism:
darian$ jr IfDef
javac IfDef.java
java IfDef
Hello, World
darian$ strings IfDef.class | grep Life # not found!
darian$ javac IfDef.java # try another compiler
darian$ strings IfDef.class | grep Life # still not found!
darian$
What if we want to use debugging code similar to this but have the condition applied at
runtime? We can use System.properties (see Getting Information from System Properties )
to fetch a variable. Instead of using this conditional compilation mechanism, you may want
to leave your debugging statements in the code but enable them only at runtime when a prob-
lem surfaces. This is a good technique for all but the most compute-intensive applications,
because the overhead of a simple if statement is not all that great. Let's combine the flexibil-
ity of runtime checking with the simple if statement to debug a hypothetical fetch() meth-
od (part of Fetch.java ):
String name = "poem";
if (System.getProperty("debug.fetch") != null) {
System.err.println("Fetching " + name);
}
value = fetch(name);
Search WWH ::




Custom Search