cuihtlauac cuihtlauac - 6 months ago 10
Java Question

How to enable “replace by (Java 8) method reference” feature in Android Studio

IntelliJ can refactor this:

class Foo {
static void bar() {}
static {
new Runnable() {
@Override
public void run() {
Foo.bar();
}
}.run();
}
}


into that:

class Foo {
static void bar() {}
static {
((Runnable) Foo::bar).run();
}
}


Isn't it nicer? (thanks Anna Kozlova). Now that Android supports Java 8, how can I do that in Android Studio?

Answer

You need to do several things.

First you need to be using a JDK 1.8 (amazing, no?)

Second condition is to set your targetSdkVersion and compileSdkVersion to 23 in your build.gradle file.

Then you need to enable Java 8 features by adding in the defaultConfig of your build.gradle file

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

Finally you also need to enable the Jack toolchain by adding the following lines to the same section of your build.gradle file:

jackOptions {
      enabled true
}

You also need buildToolsVersion set to 24 and above for your project to build.

You can then enjoy the full Java 8 features and related refactoring suggestion in Android Studio.