lightyears99
lightyears99

Reputation: 111

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.

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?

Upvotes: 0

Views: 666

Answers (1)

Nikky
Nikky

Reputation: 518

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.

Upvotes: 0

Related Questions