gpt4 book ai didi

gradle - 构建应用程序时如何使用 KotlinPoet 生成代码? (毕业)

转载 作者:行者123 更新时间:2023-12-02 12:59:05 26 4
gpt4 key购买 nike

我是使用 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)
...
..
.

我想建立一个名为 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
}
...
..
.

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

谢谢并恭祝安康。

最佳答案

在我看来 Kotlin 诗人 缺乏关于如何将其集成到项目中的任何示例的文档。

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

我用 custom Gradle tasks 做到了.

中某处有一个应用程序/库/子项目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)
}

现在让 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
}
}

在 Android Studio/Intellij IDEA 中打开 Gradle tool window , 寻找新群 kotlinpoet (没有 group 任务将在 others 部分),并执行任务 saveGeneratedSources .

关于gradle - 构建应用程序时如何使用 KotlinPoet 生成代码? (毕业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com