只在为 Android 编译时才编译源代码?

Compile source code only when compiled for Android?

我正在为 android 和 PC 制作游戏,并且必须导入 android 独有的内容以及包含仅适用于 android[=12 的代码的编写方法=]

我希望能够做这样的事情,所以在我编译非android版本的情况下,它不会给出编译错误

boolean android = "The Android Project".equals(System.getProperty("java.specification.vendor"));
void setup(){
    if (android)
        importAndroid();
    //other setup stuff irrelevant to the question
}

void importAndroid(){
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;
    import android.content.Context;
    import android.app.Activity;
}

你不能像那样有条件地导入 classes。

相反,您应该将同时在桌面和 Java 上运行的代码封装到它自己的 class(或多个 class 中),您可以将其用作库。然后构建一个桌面应用程序和一个 Android 应用程序,其中仅包含特定于一个版本的代码。两个特定于平台的项目都将共享代码用作库。

如果您需要从共享代码中调用特定于平台的代码,请通过接口执行此操作,这样您就不必关心共享代码中的特定于平台的代码。像这样:

public interface Printer {
  public void print(String s);
}

然后在该接口的实现中实现特定于平台的代码:

public class DesktopPrinter implements Printer {
  public void print(String s) {
    System.out.println(s);
  }
}


public class AndroidPrinter implements Printer {
  public void print(String s) {
    Log.d("MyApp", s);
  }
}

然后在您的处理代码中,您只会使用接口:

Printer printer;

void setPrinter(Printer printer) {
  this.printer = printer;
}

void draw(){
  printer.print("in draw");
}

然后在特定于平台的代码中创建这些 classes 的实例并将其传递到您的草图中 class。