0

我有一个独立的 Gradle 插件,其中包含自定义任务类型:

gradle-conventions/build.gradle

plugins {
  id 'groovy-gradle-plugin'
  id 'maven-publish'
}

group = 'com.example'
version = '1.0'

publishing {
  repositories {
    maven {
      url = uri('/path/to/repo')
    }
  }
}

gradle-conventions/src/main/groovy/com.example.my-conventions.gradle

abstract class CustomTask extends DefaultTask {
    @TaskAction
    def hello() {
        println "hello"
    }
}

我可以使用另一个项目中的插件,但是如何注册一个CustomTask?像这样的东西:

项目/build.gradle

plugins {                                                                       
  id 'com.example.my-conventions' version '1.0'
}

// how do I reference CustomTask here?
tasks.register('myCustomTask', com.example.CustomTask) {
  // ...
}

是否可以从自定义插件导出自定义任务?或者我必须 使用该buildscript机制使用自定义任务吗?

4

1 回答 1

1

检查gradle-conventions-1.0.jar后,似乎自定义任务类属于默认包,所以我可以注册任务如下:

项目/build.gradle

plugins {                                                                       
  id 'com.example.my-conventions' version '1.0'
}

tasks.register('myCustomTask', CustomTask) {
  // ...
}

但这仅适用com.example.my-conventions.gradle于除类本身之外的常规代码,否则我会收到错误消息:

An exception occurred applying plugin request [id: 'com.example.my-conventions', version: '1.0']
> Failed to apply plugin 'com.example.my-conventions'.
   > java.lang.ClassNotFoundException: precompiled_ComExampleMyConventions

这种方法避免了依赖buildscript机制(在 Gradle 文档中不推荐)。

于 2021-05-27T13:32:32.823 回答