简体   繁体   English

Kotlin 注释处理器不会为生成的文件添加导入

[英]Kotlin Annotation processor doesn't add import for generated files

I have an Annotation-processor, which should generate a class MyGeneratedClass containing a variable of another class MyEntity .我有一个注释处理器,它应该生成一个 class MyGeneratedClass包含另一个 class MyEntity的变量。

My code inside the process function:我在process function 中的代码:


    val elementsWithAnnotation = roundEnv.getElementsAnnotatedWith(MyClass::class.java)
        if (elementsWithAnnotation.isEmpty()) {
            return true
        }
        val fileName = "MyGeneratedClass"
        val packageName = "me.myname.sdk.generated"
        val classBuilder = TypeSpec.classBuilder(fileName)

        for (element in elementsWithAnnotation) {
            val ann = element.getAnnotation(MyClass::class.java)
            println("package: "+ ann.javaClass.packageName)

            val variableBuilder =
                PropertySpec.varBuilder(
                    name = element.simpleName.toString(),
                    type = ClassName("", element.asType().asTypeName().asNullable().toString()),
                    ).initializer("null")
           



            classBuilder
                .addProperty(variableBuilder.build())
        }


        val file = FileSpec.builder(packageName, fileName)
            .addType(classBuilder.build())
            .build()
        val generatedDirectory = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME]
        file.writeTo(File(generatedDirectory, "$fileName.kt"))
        return true

But the generated code misses the import MyEntity但是生成的代码错过了import MyEntity

package me.myname.sdk.generated

class MyGeneratedClass {
    var MyEntity: MyEntity? = null
}

When looking inside the generated file, IntelliJ suggests me to import MyEntity , which resolves the error.在查看生成的文件时,IntelliJ 建议我导入MyEntity ,这可以解决错误。 But how can I achieve, that the import MyEntity statement is being added when generating the file?但是,如何在生成文件时添加import MyEntity语句?

looking at the kotlinpoet documentation https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index.html looking at the kotlinpoet documentation https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index.html

seems like the first argument in your code, which is a empty string is the package name you are missing in the generated code.似乎是您的代码中的第一个参数,它是一个空字符串,是您在生成的代码中缺少的 package 名称。

in my experience kotlinpoet is much happier to generate code that in in packages.以我的经验,kotlinpoet 更乐意在包中生成代码。 it sometimes does silly things with types in the root/default package.它有时会对根/默认 package 中的类型做一些愚蠢的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM