Java (Eclipse) - Conditional compilation

后端 未结 3 1540
慢半拍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 :)

提交回复
热议问题