如何在gradle中创建自定义任务,将java和kotlin代码打包到jar中?

如何在gradle中创建自定义任务,将java和kotlin代码打包到jar中?,gradle,kotlin,Gradle,Kotlin,我们有一个多模块的设置,我们在模块之间共享一些测试类(主要是伪造的实现)。我们当前的解决方案(您可以在下面找到)只适用于用Java编写的类,但我们也在考虑支持共享kotlin类 if (isAndroidLibrary()) { task compileTestCommonJar(type: JavaCompile) { classpath = compileDebugUnitTestJavaWithJavac.classpath source sourc

我们有一个多模块的设置,我们在模块之间共享一些测试类(主要是伪造的实现)。我们当前的解决方案(您可以在下面找到)只适用于用Java编写的类,但我们也在考虑支持共享kotlin类

if (isAndroidLibrary()) {
    task compileTestCommonJar(type: JavaCompile) {
        classpath = compileDebugUnitTestJavaWithJavac.classpath
        source sourceSets.testShared.java.srcDirs
        destinationDir = file('build/testCommon')
    }
    taskToDependOn = compileDebugUnitTestSources
} else {
    task compileTestCommonJar(type: JavaCompile) {
        classpath = compileTestJava.classpath
        source sourceSets.testShared.java.srcDirs
        destinationDir = file('build/testCommon')
    }
    taskToDependOn = testClasses
}

task testJar(type: Jar, dependsOn: taskToDependOn) {
    classifier = 'tests'
    from compileTestCommonJar.outputs
}

如何修改
compileTestCommonJar
使其支持kotlin?

任务compileTestCommonJar(类型:JavaCompile)只编译.java文件,因为它是
JavaCompile
类型的任务

还有
kotluncompile
任务,所以您需要合并它,它基本上与
JavaCompile
类似,但只编译.kt文件

我说我不会使用任务系统来共享依赖关系,我会使用单独的模块,并使用默认的
compileTestKotlin
compileTestJava
任务的
输出

以下是我们要做的:

  • 在具有共享测试类的模块中,将
    test
    源代码集输出打包到一个jar中
  • 在依赖于共享类的模块中

  • PS:老实说,我更希望有一个带有公共测试类的单独Gradle模块,因为它是更显式的解决方案。

    无法为project获取未知属性“KotlinCompile”:类型为org.Gradle.api.project的project。您需要导入它org.jetbrains.kotlin.Gradle.dsl.KotlinCompile非常感谢,但是我还是遇到了一些问题:
    无法为抽象类“KotlinCompile”创建代理类
    我很确定我在创建问题之前尝试过这个,但是无论如何感谢你的建议实际上我相信导入应该是
    org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    ,not
    org.jetbrains.kotlin.gradle.dsl.KotlinCompile
    @sschuberth如何导入
    org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    idea似乎无法解决这个问题。你知道怎么做吗?当你说在模块之间共享一些测试类时,你的确切意思是什么?在不同项目的测试中使用的是实际测试还是类?只是类,伪造实现以避免使用mocksSo基本上您的测试依赖于这些类?为什么不在一个额外的模块中编译这些类,并将此模块作为
    testCompile
    testImplementation
    依赖项添加到其他模块中。我已经有太多的模块了,这将是一个解决办法。我已经有了一个使用Java文件的工作解决方案。。。只是想通过使用代码重用模块编译Kotlin代码使其更加灵活并不是一种解决办法。相反,在Gradle构建中手动和有条件地创建任务是其中之一。
    configurations { tests }
    ...
    task testJar(type: Jar, dependsOn: testClasses) {
        baseName = "test-${project.archivesBaseName}"
        from sourceSets.test.output
    }
    
    artifacts { tests testJar }
    
    dependencies {
      testCompile project(path: ":my-project-with-shared-test-classes", configuration: "tests")
    }