Is it possible in Java to do a sort of #ifdef thing, like in C/C++?
Example:
class Test
{
public static final boolean ANDROID = false;
public Test()
{
if (ANDROID)
{
// do stuff that won't compile if not on android
}
else
{
// do stuff that should be only done on desktop
}
}
}
Note that even if ANDROID
is false
, as in the example, it will still try to compile the code inside of the if
, even though it won't (and shouldn't) compile.
I'm looking for a way to do conditional compilation -- the compiler shouldn't even look at the if
if ANDROID
is false
.
The context of my question is that I have a Processing application in Eclipse. I'm using both normal Processing and Processing for Android in two separate projects, but I want to be able to move the source code of the projects between one another without having compiler errors. For example, I want to be able to have source code files that I can move from the Android project to the desktop project and only have to change a couple of things -- for example, changing ANDROID = true
to ANDROID = false
.
I really need it to be conditional compilation because when I copy the source code from the Android project to the desktop project, the desktop libraries obviously won't include Android libraries, and then the source code won't even compile.
EDIT: So now that I know that there is no preprocessor in Java, my question is: is there any other way to have this functionality in my projects (being able to copy source code from one to the other with only very minor changes) without having to manually [un]comment specific pieces of code and having to remember where those are?
EDIT 2: This is not a duplicate of the other question because my question includes code that may have compiler errors in it, whereas the question that this was closed as a duplicate of does not. (That other question concerns only code that would compile fine even without #ifdef
s.) To explain, the most highly rated (and accepted) answer for the other question talks about code that is compiled, but is simply not emitted in the bytecode. However, my question concerns code that would not even compile originally.
As Java does not natively include a preprocessor, it would be incumbent upon you to manually execute one before compiling. The c preprocessor is m4, which you can run yourself.