Search code examples
kotlinannotation-processingkotlinpoet

KotlinPoet how to use FunSpec.overriding when the class is not present?


I have a package name and a class name as Strings but I don't have the class specifically in my annotation processor. I need to use:

FunSpec.overriding(getOnlyElement(methodsIn(//stuck here)))

The stuck here should be a setOf ExecutableElements? How can I do this?

I've also checked here, but no so much luck.


Solution

  • First you need to obtain a TypeElement using the package and class name (you will need a ProcessingEnvironment instance for that).

    fun getTypeElement(
            processingEnvironment: ProcessingEnvironment,
            packageName: String,
            className: String
    ): TypeElement {
        return processingEnvironment.elementUtils.getTypeElement("$packageName.$className")
    }
    

    Then you can simply access the enclosedElements in the TypeElement:

    val typeElement = getTypeElement(processingEnv, packageName, className)
    
    FunSpec.overriding(getOnlyElement(methodsIn(typeElement.enclosedElements)))