Is there way to use Java 8 features with Android library project?

后端 未结 2 359
野性不改
野性不改 2021-02-04 12:16

I followed the Android Java 8 Features manual. It works well for Android application project. But when I try to use it with Android library project I get

Error:L         


        
相关标签:
2条回答
  • 2021-02-04 12:43

    I had the same issue and tried different approaches. It now works for me without using retrolambda (which produced some weird error during runtime). Also Jack is not active for the same reason you already mentioned. There is an interesting bug post at google.com about this topic: https://code.google.com/p/android/issues/detail?id=211386

    Here is my build.gradle script, I used the workaround from the bug post to fix the "MethodType not found" exception during compilation.

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:2.1.2'
        }
    }
    apply plugin: 'com.android.library'
    
    repositories {
        mavenCentral()
    }
    
    // Java8 not fully supported in library projects yet, https://code.google.com/p/android/issues/detail?id=211386
    // this is a temporary workaround to get at least lambdas compiling
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xbootclasspath/a:" + System.properties.get("java.home") + "/lib/rt.jar"
        }
    }
    
    android {
        compileSdkVersion 24
        buildToolsVersion "24"
    
        defaultConfig {
            minSdkVersion 10
            targetSdkVersion 24
        }
    
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    
    0 讨论(0)
  • 2021-02-04 12:45

    This sure has been a long ride. I tried all possible combinations of the gradle plugin, the experimental gradle plugin + retrolambda + Jack etc, but with no luck. Until now. From Android Studio 3.0 Preview 1 or later (and, consequently, the Android Gradle plugin 3.0.0-alpha1 or later), the Jack toolchain is deprecated and replaced by some new bytecode transformation - sugaring, used in conjunction with the standard javac compiler.

    With this setup I've personally (finally!!!) been successful in using Java 8 features such as lambdas in a library project.

    This page has all the techy info as well as migration help etc: https://developer.android.com/studio/write/java8-support.html

    0 讨论(0)
提交回复
热议问题