Kotlinpoet如何添加内部对象类定义?

时间:2018-09-06 20:01:04

标签: kotlin code-generation kotlinpoet

我正在尝试在类内部生成对象定义。这是一个精简版本:

class SomeClass {

   // need to figure out how to generate this
   companion object {

      // and this
      object Constants {
         val SOME_CONSTANT = "CONSTANT VALUE"
      }
   }
}

1 个答案:

答案 0 :(得分:1)

您可以使用object创建TypeSpec.objecBuilder,然后使用addType将其嵌套在类中,例如:

val constants = TypeSpec.objectBuilder("Constants")
        .addProperty(PropertySpec.builder("SOME_CONSTANT", String::class)
                .mutable(false)
                .initializer("CONSTANT VALUE")
                .build())
        .build()

val someClass = TypeSpec.classBuilder("SomeClass")
        .addType(constants)
        .build()