In C/C++ there is a construct which allows you to conditionally compile code. Yes I am talking about the
#ifdef... #endif Java doesn’t have an equivalent. But you can use the following clever trick to achieve the same functionality.
Why conditionally compile code?
So before we proceed, you might ask me, why we need to do conditionally compiling? There are couple of reasons, but the main reason which motivated me to look for the solution is to conditionally enable debug statements. You can say that we can probably use a boolean variable or a function call, to determine whether we need to output the debug statement or not. But if the number of debug statements is high then they could add up.
Setting up final boolean variable
So the trick is simple. You have to create a if statement with a boolean private variable and if you make the boolean private variable as final and set the value to false, then at compile time, the compiler will be able to determine that these code branches are unreachable and will not include them as part of the compiled code.
The following sample code explains this trick.
- 10 more open source Android apps which every developer must look into
- Right Click on JComboBox [Java Swing component]
- Developing Android Apps - Part 2 - Week one - My notes
- Developing Android Apps - Part 2 – Overview - My notes
- Free online course on developing android applications using Java - Part 2
- 10 Open Source Android Apps which every Android developer must look into
- Developing Android applications in Java - Session 3 - My notes
- Using ArrayAdapter and ListView in Android Applications
- Developing Android applications in Java - Session 2 - My notes