2

In my search for a #ifdef-equivalent in Java, I found this great thread that describes a way to do conditional compilation: #ifdef #ifndef in Java

What I don't understand is how this really works:

  1. Why is the 2nd form (System.getProperty) better than the 1st one (false/true)?
  2. "fast" is not one of Java's predefined properties. This probably means that I have to define it in my code somewhere. What is the best place to do this in an Android app? Is onCreate() a good place?
Community
  • 1
  • 1
uTubeFan
  • 6,664
  • 12
  • 41
  • 65

2 Answers2

3

1) The first one will be optimized by the compiler. That is, you'll set the boolean property to 'true' and the compiler will discard the else-branch of conditionals. If you set it to false, the then-branch will be discarded. You have to recompile your code if you want to switch fast to slow or vice versa.

2) You'll have to define the system property when you launch your app. Setting VM-wide properties is a previleged operation. I'm not an android expert but I doubt that you can set these in the onCreate-event of an android app. The core idea behind System.getProperty is, that you'll be able to switch the application mode when you start the virtual machine by passing an additional command line argument like -Dfast=true.

Sebastian Zarnekow
  • 6,609
  • 20
  • 23
  • Thank you! 1++ Do I understand correctly from your answer that the 2nd form (which uses System.getProperty) is **not** optimized by the compiler? – uTubeFan Apr 26 '11 at 20:31
  • Yes, System.getProperty() is a method invocation. The compiler cannot predict the result of this invocation and will thereby not remove one of the branches statically. – Sebastian Zarnekow Apr 26 '11 at 20:35
1
  1. The 2nd is more flexible, since you could decide to switch something on or off while starting. The 1st example will be optimized away, so you need to recompile to change the value.

  2. A Systemproperty is set by -Dproperty=value (Note: before command line arguments which are passed to the main method)

stacker
  • 68,052
  • 28
  • 140
  • 210
  • Thank you too for this great clarification. I already accepted the answer by @Sebastian so please accept my +1 as a token of my appreciation. – uTubeFan Apr 26 '11 at 20:33