Search code examples
javaandroideclipsejava-meconditional-compilation

Java (Eclipse) - Conditional compilation


I have a java project that is referenced in j2me project and in android project. In this project i would like to use conditional compilation.

Something like...

//#if android
...
//#endif

//if j2me
...
//#endif

I have been reading about this but i did not find anything useful yet.


Solution

  • You could use Antenna (there is a plugin for Eclipse, and you can use it with the Ant build system). I'm using it in my projects in a way you've described and it works perfectly :)

    EDIT: here is the example related to @WhiteFang34 solution that is a way to go:

    In your core project:

    //base class Base.java
    public abstract class Base {
        public static Base getInstance() 
        {
            //#ifdef ANDROID
            return new AndroidBaseImpl();
            //#elif J2ME
            return new J2MEBaseImpl();
            //#endif
        }
    
        public abstract void doSomething();
    }
    
    //Android specific implementation AndroidBaseImpl.java
    //#ifdef ANDROID
    public class AndroidBaseImpl extends Base {
        public void doSomething() {
         //Android code
        }
    }
    //#endif
    
    //J2ME specific implementation J2MEBaseImpl.java
    //#ifdef J2ME
    public class J2MEBaseImpl extends Base {
        public void doSomething() {
            // J2Me code
        }
    }
    //#endif
    

    In your project that uses the core project:

    public class App {
    
        public void something {
            // Depends on the preprocessor symbol you used to build a project
            Base.getInstance().doSomething();
        }
    }
    

    Than if you want to build for the Android, you just define ANDROID preprocessor symbol or J2ME if you want to do a build for a J2ME platform...

    Anyway, I hope it helps :)