Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any #IF and #CONST .NET equivalent in Java/Android? [duplicate]

I have a project in which there are many codes only available in determined version, and when I fix a bug I have to fix them in all copies. It's very inconvenient.

Is there any #IF and #CONST in Java, that if the #IF clause is false, the code won't be compiled?

like image 359
AndBie Avatar asked Jun 24 '11 15:06

AndBie


1 Answers

There's no "official" pre-processor for Java, and there is no third-party one that's widely used.

But nothing stops you from using any pre-processor you want on your code, if you're willing to live with the handicap that IDEs and many other tools won't handle it correctly.

That being said, you don't usually need it in Java either. You'd rather provide multiple implementations of a common interface (or classes extending a common base class) and choose between them at runtime.

There is, however a limited form of conditional compilation by using compile-time constant boolean flags:

 static final DEBUG = false;

 public void frobnicate() {
   if (DEBUG) {
     doExpensiveFrobnicationDebugOperation();
   }
   doActualFrobnication();
 }

This code will result in the expensive method call not being compiled into the bytecode of the resulting .class file.

like image 124
Joachim Sauer Avatar answered Oct 01 '22 07:10

Joachim Sauer