跳到内容

KotlinPoet

KotlinPoet 是用于生成 .kt 源文件的 Kotlin 和 Java API。

在进行注解处理或与元数据文件(例如,数据库模式、协议格式)交互时,生成源文件非常有用。通过生成代码,你可以消除编写样板代码的需要,同时保持元数据的单一真实来源。

示例

这是一个 HelloWorld 文件

class Greeter(val name: String) {
  fun greet() {
    println("""Hello, $name""")
  }
}

fun main(vararg args: String) {
  Greeter(args[0]).greet()
}

这是使用 KotlinPoet 生成它的代码

val greeterClass = ClassName("", "Greeter")
val file = FileSpec.builder("", "HelloWorld")
  .addType(
    TypeSpec.classBuilder("Greeter")
      .primaryConstructor(
        FunSpec.constructorBuilder()
          .addParameter("name", String::class)
          .build()
      )
      .addProperty(
        PropertySpec.builder("name", String::class)
          .initializer("name")
          .build()
      )
      .addFunction(
        FunSpec.builder("greet")
          .addStatement("println(%P)", "Hello, \$name")
          .build()
      )
      .build()
  )
  .addFunction(
    FunSpec.builder("main")
      .addParameter("args", String::class, VARARG)
      .addStatement("%T(args[0]).greet()", greeterClass)
      .build()
  )
  .build()

file.writeTo(System.out)

KDoc 包含了完整的 KotlinPoet API,它受到 JavaPoet 的启发。

注意: 为了最大限度地提高可移植性,KotlinPoet 生成的代码带有明确的可见性修饰符。这确保了与标准 Kotlin 项目以及使用 explicit API mode 的项目的兼容性。文档中的示例为了简洁起见省略了这些修饰符。

下载

Maven Central

下载 最新的 .jar 文件 或通过 Maven 依赖

<dependency>
  <groupId>com.squareup</groupId>
  <artifactId>kotlinpoet-jvm</artifactId>
  <version>[version]</version>
</dependency>

或 Gradle

implementation("com.squareup:kotlinpoet:[version]")

开发版本的快照可在 Sonatype 的 snapshots 仓库 中找到。

许可证

Copyright 2017 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   https://apache.ac.cn/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.