0

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?

lightyears99
  • 101
  • 7

1 Answers1

0

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.

Nikky
  • 498
  • 2
  • 9
  • if I use this: `type=ClassName("MyEntity",element.....)` , It adds `import MyEntity.MyEntity?` to the file, which is also wrong. Correct would be: `import MyEntity`. If i leave it blank as shown in the original post, there is no `import` added at all. – lightyears99 Sep 03 '22 at 18:07