Kotlin Annotation processor doesn't add import for generated files

499 views Asked by At

I have an Annotation-processor, which should generate a class MyGeneratedClass containing a variable of another class MyEntity.

My code inside the processfunction:


    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

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. But how can I achieve, that the import MyEntity statement is being added when generating the file?

1

There are 1 answers

1
Nikky On

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.

in my experience kotlinpoet is much happier to generate code that in in packages. it sometimes does silly things with types in the root/default package.