Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using Java 8 Features in Android Studio 2

Author: Ian Darwin -- Published? true -- FormatLanguage: A

Problem:

You are using Java 8, the current version of Java as of 2015, in your other work and would like to use it in Android as well.

Solution:

Enable the "Jack" compiler chain, and use the subset of Java 8 that is supported, in Android Studio.

Discussion:

With Android N, the Android team has started moving to the current release of Java, partially and incrementally. Note that you must have the Java 8 SDK installed in order to compile for Android N, even if you are not using any of these features! "Jack" (Java compiler kit?) is a new toolchain, which compiles Java code into its own format - there is no more class file to Dex translation. This should be faster, but also means that tools like findbugs which read the .class files will no longer work without an extra compilation step.

To use Jack, you must have Android Studio 2.1 or later and the Build Tools package 24 or later. And you must set your Source and Target compilation level to 1.8, either in build.gradle or in the module settings. Plus, as of the current preview, you must add the jackOptions enable entry manually to build.gradle, inside your defaultConfig entry:

android {
    defaultConfig {
        // Other defaults here...
        // Enable 'jack'
        jackOptions {
            enabled true
        }
    }
    // And if you prefer to set these manually:
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

As of this writing (June 2016), the language features shown in java8lang and the API featues in <> are working.


Java 8 Language Features

  • Lambda expressions (also available on API level 23 and lower)
  • Method References (also available on API level 23 and lower)
  • Default and static interface methods
  • Multiple use of annotations Of these, Lambda expressions are the best known and arguably the most important, but the others are significant.


    Java 8 APIs

  • Reflection and language-related APIs: java.lang.FunctionalInterface java.lang.annotation.Repeatable java.lang.reflect.Method.isDefault() Reflection APIs related to multiply-used annotations, such as AnnotatedElement.getAnnotationsByType(Class)
  • Utility APIs: java.util.function java.util.stream

    These utility APIs are in support of functional programming and composition.

    There are many other important APIs which do not appear to be slated for Android any time soon, such as the very useful Date and Time API java.time. Of course, only time will tell if these get included.

    See Also:

    This page listed the Java 8 features in the preview release.
    No records found.