Using Java 8 Features in Android Studio 2
In Chapter: Getting Started
Author: Ian Darwin ('idarwin')
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.
Enable the "Jack" compiler chain, and use the subset of Java 8 that is supported, in Android Studio.
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:
// Other defaults here...
// Enable 'jack'
// And if you prefer to set these manually:
As of this writing (June 2016), the language features shown in java8lang and the API featues in <> are working.
Java 8 Language Features
Of these, Lambda expressions are the best known and arguably the most important, but the others are significant.
- 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
Java 8 APIs
These utility APIs are in support of functional programming and composition.
- 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
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.