WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCo...

最近在升级 gradle 的时候遇到了这个问题,后来查看资料发现是从 gradle 4.10.1 及以上版本开始提示的。根据提示只要把 variant.javaCompile 改成 variant.javaCompileProvider 就行, 在我的项目中出问题的是一个三方库,出问题部分修改之前的代码如下

android.libraryVariants.all { variant ->
    def name = variant.buildType.name
    def task = project.tasks.create "jar${name.capitalize()}", Jar
    task.dependsOn variant.javaCompile
    task.from variant.javaCompile.destinationDir
    artifacts.add('archives', task)
}

修改之后

android.libraryVariants.all { variant ->
    def name = variant.buildType.name
    def task = project.tasks.create "jar${name.capitalize()}", Jar
    task.dependsOn variant.javaCompileProvider
    task.from variant.javaCompileProvider.destinationDir
    artifacts.add('archives', task)
}

在这里又遇到了一个错误,提示 unknown property 'destinationDir'

Could not get unknown property 'destinationDir' for provider(task compileDebugJavaWithJavac, class com.android.build.gradle.tasks.AndroidJavaCompile) of type org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreatingProvider_Decorated.

后来阅读源码发现 getJavaCompileProvider 获取的是一个 TaskProvider

@NonNull
@Override
public TaskProvider getJavaCompileProvider() {
    //noinspection unchecked
    return (TaskProvider) getVariantData().getTaskContainer().getJavacTask();
}

找到原因之后,最后修改的如下

android.libraryVariants.all { variant ->
    def name = variant.buildType.name
    def task = project.tasks.create "jar${name.capitalize()}", Jar
    task.dependsOn variant.javaCompileProvider
    task.from variant.javaCompileProvider.get().destinationDir
    artifacts.add('archives', task)
}

你可能感兴趣的:(WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCo...)