Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable “replace by method reference” refactoring (and Java 8 features) 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?

like image 339
cuihtlauac Avatar asked May 09 '26 11:05

cuihtlauac


1 Answers

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
}

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
}

Finally, 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.

You can read more about Java 8 features and Android in the documentation.

like image 96
Marc Poppleton Avatar answered May 12 '26 01:05

Marc Poppleton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!