当我构建应用程序时,如何使用 KotlinPoet 生成代码?(摇篮)

Tio*_*ing 7 build gradle kotlin kotlinpoet

我是 kotlinpoet 的新手,我一直在阅读文档,它似乎是一个很棒的库,但我找不到解决我的问题的示例。

我有一个依赖项lib-domain-0.1.jar,其中有业务对象,例如:

package pe.com.business.domain

data class Person(val id: Int? = null, val name: String? = null)
...
..
package pe.com.business.domain

data class Departament(val id: Int? = null, val direction: String? = null)
...
..
.
Run Code Online (Sandbox Code Playgroud)

我想构建一个新的依赖项,lib-domain-fx-0-1.jar它具有相同的域,但具有 JavaFx 属性(使用 Tornadofx),例如:

package pe.com.business.domainfx
import tornadofx.*

class Person {
  val idProperty = SimpleIntegerProperty()
  var id by idProperty

  val nameProperty = SimpleStringProperty()
  var name by nameProperty
}
...
..
package pe.com.business.domainfx
import tornadofx.*

class Departament {
  val idProperty = SimpleIntegerProperty()
  var id by idProperty

  val directionProperty = SimpleStringProperty()
  var direction by directionProperty
}
...
..
.
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何lib-domain-fx-0-1.jar通过简单地使用 gradle 构建来编译我的应用程序来生成这些文件?我的项目“lib-domain-fx-0-1.jar”只是一个库,因此它没有主类,所以我不知道从哪里开始生成代码?我见过几个例子,其中它们@Annotations在同一个项目中使用两个不同的模块,但这不是我需要的:(。我需要lib-domain-0.1.jar在另一个项目中使用 TornadoFX 将所有类转换为 JavaFx 版本 ( lib-domain-fx-0.1.jar)

感谢致敬。

Mik*_*san 7

在我看来,KotlinPoet的文档中缺少任何有关如何将其集成到项目中的示例。

正如 @Egor 提到的,问题本身相当广泛,所以我只会回答核心部分:当我使用 Gradle 构建应用程序时,如何使用KotlinPoet生成代码?

我通过自定义 Gradle 任务做到了这一点。

src/main/java/com/business/package/GenerateCode.kt中有一个应用程序/库/子项目:

package com.business.package

import com.squareup.kotlinpoet.*

fun main() {
    // using kotlinpoet here

    // in the end wrap everything into FileSpec
    val kotlinFile: FileSpec = ...
    // and output result to stdout
    kotlinFile.writeTo(System.out)
}
Run Code Online (Sandbox Code Playgroud)

现在让 Gradle 创建一个包含生成输出的文件。添加到build.gradle

task runGenerator(type: JavaExec) {
    group = 'kotlinpoet'
    classpath = sourceSets.main.runtimeClasspath
    main = 'com.business.package.GenerateCodeKt'
    // store the output instead of printing to the console:
    standardOutput = new ByteArrayOutputStream()
    // extension method genSource.output() can be used to obtain the output:
    doLast {
        ext.generated = standardOutput.toString()
    }
}

task saveGeneratedSources(dependsOn: runRatioGenerator) {
    group = 'kotlinpoet'
    // use build directory
    //def outputDir = new File("/${buildDir}/generated-sources")
    // or add to existing source files
    def outputDir = new File(sourceSets.main.java.srcDirs.first(), "com/business/package")
    def outputFile = new File(outputDir, "Generated.kt")
    doLast {
        if(!outputDir.exists()) {
            outputDir.mkdirs()
        }
        outputFile.text = tasks.runGenerator.generated
    }
}
Run Code Online (Sandbox Code Playgroud)

在Android Studio / Intellij IDEA中打开Gradle工具窗口,找到新组kotlinpoet(没有group任务的将在该others部分中),并执行任务saveGeneratedSources