简体   繁体   中英

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.

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 :)

Perhaps you should consider creating interfaces around the logic that's specific to a profile (J2ME, Android or other in the future). Then create concrete implementations of your interface for each profile. Any common parts you could split out into an abstract base class for both implementations to extend. This way your logic for each profile is nicely separated for different concerns. For each profile just build the appropriate set of classes (you could separate them by package for example). It'll be easier to maintain, debug, test and understand in the long run.

Eclipse MTJ project provides preprocessing support as documented . This support was mainly targeted for tackling fragmentation problems on JavaME. I have not tested the preprocessing support together with the Android tooling but it may just work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM