Java (Eclipse) - Conditional compilation

后端 未结 3 1521
慢半拍i
慢半拍i 2021-01-01 05:11

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...

相关标签:
3条回答
  • 2021-01-01 05:53

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

    0 讨论(0)
  • 2021-01-01 06:03

    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.

    0 讨论(0)
  • 2021-01-01 06:13

    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.

    0 讨论(0)
提交回复
热议问题