【问题标题】:How to get parameters of a groovy class inside build.gradle(app) to a custom gradle plugin如何将 build.gradle(app) 中的 groovy 类的参数获取到自定义 gradle 插件
【发布时间】:2021-04-07 22:20:54
【问题描述】:

我创建了一个用 Kotlin 编写的用于 android 的自定义 gradle 插件。插件工作正常。我缺少的一件事是从我的 Applications build.gradle(应用级别)中的类中获取参数。

所以我将 MyPlugin 应用到应用程序。

build.gradle(应用级别)

plugins{
   id 'com.example.MyPlugin'
}
....
....
ArchiveConfig{
   username 'James'
   password '12345678'
   debugApk false
}

在 MyPlugin 项目中的 MyPlugin.kt 中

open class MyPlugin : Plugin<Project>{

   val archiveConfig: ArchiveConfig = project.extensions.create("ArchiveConfig", ArchiveConfig())   

   override fun apply(p : Project) {
      //some code
   }
}

//I believe here I should somehow fetch that ArchiveConfig values from build.gradle which is inside

open class ArchiveConfig(var username: String? = null
                         var password: String? = null
                         vardebugApk: Boolean = false) : GroovyObjectSupport() {
   //do something with data in plugin
}

如果我采用所描述的方法,我会得到一个错误

找不到参数 [...] 的方法 ArchiveConfig()

先谢谢了!

【问题讨论】:

  • 你要找的是一个扩展:docs.gradle.org/current/userguide/…
  • @tim_yates 非常感谢您对我的问题感兴趣。在阅读了您提供的链接后,我找到了一个解决方案,并将其发布在这里作为答案。再次非常感谢! :)

标签: android kotlin gradle groovy


【解决方案1】:

根据@tim_yates 和他的扩展文档链接。

为了自定义我们的自定义插件的行为,或者换句话说,如果我们想从我们正在处理的应用程序中发送一些参数,从 build.gradle 到自定义插件,然后在自定义插件中使用这些参数,我们必须使用 扩展对象

使用示例如下:

应用程序 build.gradle(应用程序级别)

//here we apply our plugin
plugins{
 id 'com.example.MyPlugin'
}
....
....
//groovy class whose parameters we want to "send" to CustomPlugin for it to do some work
ArchiveConfig{
   username 'James'
   password '12345678'
}

在 CustomPlugin 项目中的 MyPlugin.kt 中

 open class MyPluginExtension{
 var username : String = ""
 var password : String = ""
 }

 class MyPlugin : Plugin<Project>{
    override fun apply(p : Project) {
        val extension = project.extensions.create<MyPluginExtension>("ArchiveConfig")
    
     //do stuff with variables from ArchiveConfig
     //you access them with following

     val user = extension.username
     val pw = extension.password
    }
 }

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多