简体   繁体   中英

Java Android - Defining Imports

I have following problem: I do have a class, common.java, which will be used by an Android application but also by a Java application. This class imports an android specific class (android.*).

If I want to build the Java application it does throw the error of a not existing import, of course. Programmatically I do all my Android specific stuff in an if clause:

if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) {
  //Android specific stuff
}

So: Is there a way, that I can import the Android classes also only if i'm building the android app? Like an if clause around the imports?

if(System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) {
   import ...
   import ...
}

Hopefully my problem is clear. Thanks!!

you have to splitt common into portable and os-specific code like this:

// has no android or j2se specific code
public class common {
    public void someCommonfunction() {...someOsSpecificcode(); ...}
    protected abstract void someOsSpecificcode();
}

// has android specific code
public class commonAndroid extends common {
    protected void someOsSpecificcode() { /* android specific implementation */ }
}

// has j2se specific code
public class commonJ2se extends common {
    protected void someOsSpecificcode() { /* j2se specific implementation */ }
}

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