Good programming practices

Java code conditional compilation

September 8th, 2011

Java language doesn’t have a preprocessor like C. But compiler optimize the code – if it’s sure, that code can’t be reached, it will not be included in the output byte code. An optional code can be placed inside if statement or by tertiary statement, where condition can be evaluated by compiler.

The condition is usually a boolean variable. It must be declared final, and optionally – static. Inside a statement can be any code, the same like in any if statement. Thus, there can be even a anonymous or local class but not a method itself. Try to use the code below. Compile it, see output classes, then change variable values and check it again.

  1. package eu.standardcode.example;
  3. public class ConditionalCompilation {
  5. private static final boolean COMPILE_ANONUMOUS = false;
  6. private static final boolean COMPILE_LOCAL = false;
  7. private static final boolean TERTIARY = true;
  9. public static void main(String[] args) {
  11. new Thread(new Runnable() {
  13. public void run() {
  14. print("Anonymous");
  15. }
  16. }).start();
  17. }
  18. if (COMPILE_LOCAL) {
  19. class Local implements Runnable {
  21. public void run() {
  22. print("Local");
  23. }
  24. }
  25. new Thread(new Local()).start();
  26. }
  27. print(TERTIARY ? "Will be in .class file" : "Only in source code");
  28. }
  30. static void print(String msg) {
  31. System.out.println(msg);
  32. }
  33. }

When variables are false, there will be only main class ConditionalCompilation. When they are true, you will see two more files: ConditionalCompilation$1.class (anonymouse) and ConditionalCompilation$1Local.class (local). Inside ConditionalCompilation.class file there will be only one of String after “TERTIARY ?”.

As condition you can use also some expressions like (Byte.SIZE == 8) (always true) or (COMPILE_LOCAL && COMPILE_ANONUMOUS). Conditional compilation can be useful to build different versions of software from one source code or for debugging.

Leave a Response