有一个具有ID(“com.my.plugin”)的gradle插件。

使用此插件的项目具有以下build.gradle文件:

...
apply plugin: 'com.my.plugin'
...
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "com.my.plugin.junit4.MyCustomRunner"
        ...
    }
    ...
}
...
dependencies {
    ...
    androidTestImplementation com.my:plugin-junit4:1.0.0-alpha04
    ...
}
...

实现该插件的类如下:
class MyPlugin: Plugin <Project> {
    override fun apply (project: Project) {
        project.afterEvaluate {
            // here I need to read testInstrumentationRunner value declared
            // in the defaultConfig block of the build.gradle file
            // also here I need to read androidTestImplementation value declared
            // in the dependencies block of the build.gradle file
        }
    }
}

在插件的project.afterEvaluate {...}块中,我需要检查使用此插件在项目的build.gradle文件中声明的testInstrumentationRunner和androidTestImplementation的值。怎么做?

最佳答案

由于您将Kotlin用于插件实现,因此您需要知道android { }扩展名的类型。否则,您将遇到编译错误。

本质上,您需要在插件中检索android扩展名的引用,如下所示:

project.afterEvaluate {
    // we don't know the concrete type so this will be `Object` or `Any`
    val android = project.extensions.getByName("android")

    println(android::class.java) // figure out the type

    // assume we know the type now
    val typedAndroid = project.extensions.getByType(WhateverTheType::class.java)

    // Ok now Kotlin knows of the type and its properties
    println(typedAndroid.defaultConfig.testInstrumentationRunner)
}

我不熟悉Android或它的Gradle插件。 Google只把我引到了它的Javadocs here,但没有帮助。因此上述方法可能有效也可能无效。

关于gradle - 从Gradle插件读取构建脚本块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57744598/

10-11 22:41
查看更多