从gradle插件读取构建脚本块

从gradle插件读取构建脚本块,gradle,build.gradle,gradle-plugin,Gradle,Build.gradle,Gradle Plugin,有一个id为com.my.plugin的gradle插件 使用此插件的项目具有以下build.gradle文件: ... apply plugin: 'com.my.plugin' ... android {     ...     defaultConfig {         ...         testInstrumentationRunner "com.my.plugin.junit4.MyCustomRunner"         ...     }     ... } ... d

有一个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文件中声明的TestInstrumentRunner和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插件。谷歌只让我找到了它的Javadocs,但没有任何帮助。因此,上述方法可能有效,也可能无效。

谢谢!这管用!您能告诉我如何获取androidTestImplementation的值吗?androidTestImplementation是一个。因此,只需调用project.configurations.getByNameandroidTestImplementation即可。