2017-01-03 170 views
0

我想寫使用kotlingradle的Gradle插件插件擴展的一個實例。它應該像這樣工作。同時提供配置無法創建

apply plugin: 'appenv' 

app { 
    srcLink "" 
    downloadPath "" 
} 

應該允許使用任務從srcLink和商店下載文件中downloadPathdownloadAll

我創建擴展類

open class ApplicationEnvironmentExtension { 
    val project: Any? 

    constructor(project: Any?) { 
     this.project = project 
    } 

    var srcLink: String = "" 
    var downloadPath: String = "" 
} 

創建插件類

class ApplicationEnvironmentPlugin : Plugin<Project> { 

    override fun apply(project: Project) { 
     project.extensions.create("app", ApplicationEnvironmentExtension::class.java) 
     project.task(mapOf ("type" to Download::class.java), "downloadAll") 
    } 
} 

在這裏他的t他任務

class Download : DefaultTask() { 

    @TaskAction 
    fun download() { 
     val extension = this.project.extensions.getByName("app") as ApplicationEnvironmentExtension 
     DownloadUtils.download(extension.srcLink, extension.downloadPath) 
    } 
} 

我建立它並將其添加爲jar依賴於我的項目。 要檢查是否添加了任務,請運行gradle tasks。但在我得到的錯誤

Could not create an instance of type com.lapots.gradle.plugins.appenv.ApplicationEnvironmentExtension_Decorated. 

在堆棧跟蹤我得到

Caused by: org.gradle.internal.reflect.ObjectInstantiationException: Could not create an instance of type com.lapots.gradle.plugins.appenv.ApplicationEnvironmentExtension_Decorated. 
     at org.gradle.internal.reflect.DirectInstantiator.newInstance(DirectInstantiator.java:53) 
     at org.gradle.api.internal.ClassGeneratorBackedInstantiator.newInstance(ClassGeneratorBackedInstantiator.java:36) 
     at org.gradle.api.internal.plugins.DefaultConvention.create(DefaultConvention.java:106) 
     at com.lapots.gradle.plugins.appenv.ApplicationEnvironmentPlugin.apply(ApplicationEnvironmentPlugin.kt:11) 
     at com.lapots.gradle.plugins.appenv.ApplicationEnvironmentPlugin.apply(ApplicationEnvironmentPlugin.kt:8) 
     at org.gradle.api.internal.plugins.ImperativeOnlyPluginApplicator.applyImperative(ImperativeOnlyPluginApplicator.java:35) 
     at org.gradle.api.internal.plugins.RuleBasedPluginApplicator.applyImperative(RuleBasedPluginApplicator.java:43) 
     at org.gradle.api.internal.plugins.DefaultPluginManager.doApply(DefaultPluginManager.java:144) 
     ... 58 more   
Caused by: java.lang.IllegalArgumentException: Could not find any public constructor for class com.lapots.gradle.plugins.appenv.ApplicationEnvironmentExtension_Decorated which accepts parameters []. 
     at org.gradle.internal.reflect.DirectInstantiator.newInstance(DirectInstantiator.java:44) 
     ... 65 more  

問題是什麼?我應該爲擴展提供一些附加的構造函數嗎?

回答

4

擴展需要一個默認的(無參數)構造函數。如果您確實需要爲擴展名中的值指定一個字段,則可以使用lateinit var並在插件中創建擴展名後指定它。

在這種情況下,它看起來並不像你需要你的project領域,所以你可以擺脫那個和構造。否則,如果你確實需要的領域,仍然取下的構造,但你需要做project一個變種與null的默認值。

+0

很酷。有用。 – lapots