AGP 8.0 解决 ‘kaptGenerateStubsDebugKotlin‘ task (current target is 17) 问题

AGP 升级到 8.0 后,运行项目出现了下面的问题:

Execution failed for task ':app:kaptGenerateStubsDebugKotlin'.
> 'compileDebugJavaWithJavac' task (current target is 1.8) and 'kaptGenerateStubsDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.
  Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

从 log 上看:编译 java 代码的目标版本是 1.8,而 kotlin 注解任务的目标版本是 17,由于版本不一致,所以编译失败。但是,kotlin 和 java 的 target 已经在 build.gradle 文件中设置成 1.8 了,设置方式如下:

android {
    
    
	...
    compileOptions {
    
    
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
    
    
        jvmTarget = '1.8'
    }	
}

难道这里 kotlinOptions 对 kotlin 的注解任务不起作用?根据 log 提示,从 https://kotl.in/gradle/jvm/toolchain 中看到了 kotlin 新的设置方式:

kotlin {
    
    
    jvmToolchain {
    
    
        languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>))
    }
    // Or shorter:
    jvmToolchain(<MAJOR_JDK_VERSION>)
    // For example:
    jvmToolchain(8)
}

所以,只需要在 android 节点下加入

kotlin {
    
    
	jvmToolchain(8)
}

即可。

当然还可以在 build.gradle 中添加以下代码来遍历 kotlin 的编译任务,然后把 jvmTarget 设置成 1.8:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile.class){
    
    
    kotlinOptions {
    
    
        jvmTarget = "1.8"
    }
}

猜你喜欢

转载自blog.csdn.net/niuzhucedenglu/article/details/130542999