有一个带有id的gradle插件("com.my.plugin"(。
使用此插件的项目具有以下 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插件。谷歌只是把我带到了它的Javadocs,这并没有帮助。因此,上述方法可能有效,也可能无效。