Gradle Kotlin DSL:访问settings.gradle.kts中定义的对象

时间:2019-02-09 06:32:58

标签: gradle-kotlin-dsl

我有一些在settings.gradle.kts中定义的对象。如何从build.gradle.kts获得它们?

使用普通的DSL,我可以将这些对象放在gradle.ext中,但是gradle对象似乎在Kotlin DSL中并没有额外支持(使用Gradle 5.2)。

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码访问扩展对象:

(gradle as ExtensionAware).extra["myObject"]

答案 1 :(得分:0)

我意识到这个帖子有点老了,但在过去的两周里我一直在努力解决这个问题。希望它能帮助下一个寻找这个答案的可怜的开发人员。这是如何完成的示例。

settings.gradle.kts

// // This works in settings.gradle
// gradle.ext.GLOBAL_VAR = "This is a global value"
// println("settings.gradle ::: " + gradle.GLOBAL_VAR)

// This works in settings.gradle.kts
val settingsValue = "This value was set in settings.gradle.kts"
if (gradle is ExtensionAware) {
    (gradle as ExtensionAware).extra["GLOBAL_VAR"]=settingsValue
    println("settings.gradle.kts ::: " + (gradle as ExtensionAware).extra.get("GLOBAL_VAR"))
}

build.gradle.kts

// // This works in settings.gradle
// println("build.gradle ::: " + gradle.GLOBAL_VAR)

// This works in settings.gradle.kts
if (gradle is ExtensionAware) println("build.gradle.kts ::: " + (gradle as ExtensionAware).extra.get("GLOBAL_VAR"))
  • Gradle 6.6.1 版