5

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?

trooper
  • 4,444
  • 5
  • 32
  • 32
AndBie
  • 95
  • 4

2 Answers2

6

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • That's a good answer. Much more helpful than mine anyway. +1 – Zhehao Mao Jun 24 '11 at 16:17
  • 1
    Thanks, I've known about this. However, pre-processor provides 2 benefits: The compiled file size is smaller. Second: it reduce chance the "free" version is cracked into "full" version (the second may not be a problem with Android, just with PC). Anyway, thanks for your answer :) – AndBie Jun 24 '11 at 16:18
  • 2
    @AndBie: for both of those an obfuscator might help. Not because it makes the code harder to crack (I don't really believe in that), but because it can remove dead code (even methods that are never called!). That's usually the reason why obfuscators are used on J2ME code, even when it's free/libre software. – Joachim Sauer Jun 24 '11 at 16:20
  • Thanks :) Now I have to fix a serious bug of my program. 3 copies of them :( – AndBie Jun 24 '11 at 16:23
0

There is no such thing as a preprocessor for Java, so unfortunately you cannot do conditional compilation.

Zhehao Mao
  • 1,789
  • 13
  • 13
  • Really? That's bad :( I still waiting for another answers, hope there's, or there's another solution. – AndBie Jun 24 '11 at 16:10