Is it possible to use Java 8 for Android development?

后端 未结 26 1998
礼貌的吻别
礼貌的吻别 2020-11-21 22:50

Searching the web, it is not clear if Java 8 is supported for Android development or not.

Before I download/setup Java 8, can some one point me at any \"official\" d

26条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 23:11

    I figured I would post an updated answer for those looking at for something a little more current.

    Currently Android and Android Studio are supporting a subset of Java 8 features. According to the Android documentation located on their website, Google says:

    Support for Java 8 language features requires a new compiler called Jack. Jack is supported only on Android Studio 2.1 and higher. So if you want to use Java 8 language features, you need to use Android Studio 2.1 to build your app.

    If you already have Android Studio installed, make sure you update to the latest version by clicking Help > Check for Update (on Mac, Android Studio > Check for Updates). If you don't already have the IDE installed on your workstation, download Android Studio here.

    Supported Java 8 Language Features and APIs

    Android does not support all Java 8 language features. However, the following features are available when developing apps targeting Android 7.0 (API level 24):

    • Default and static interface methods Lambda expressions (also available on API level 23 and lower)
    • Repeatable annotations
    • Method References (also available on API level 23 and lower)
    • Type Annotations (also available on API level 23 and lower)

    Additionally, the following Java 8 language APIs are also available:

    Reflection and language-related APIs:

    • java.lang.FunctionalInterface
    • java.lang.annotation.Repeatable
    • java.lang.reflect.Method.isDefault() and Reflection APIs associated with repeatable annotations, such as AnnotatedElement.getAnnotationsByType(Class)

    Utility APIs:

    • java.util.function
    • java.util.stream

    In order to use the new Java 8 language features, you need to also use the Jack toolchain. This new Android toolchain compiles Java language sources into Android-readable DEX bytecode, has its own .jack library format, and provides most toolchain features as part of a single tool: repackaging, shrinking, obfuscation and multidex.

    Here is a comparison of the two toolchains used to build Android DEX files:

    Legacy javac toolchain:
        javac (.java → .class) → dx (.class → .dex)
        New Jack toolchain:
        Jack (.java → .jack → .dex)
    

提交回复
热议问题