Search code examples
kotlinkotlin-reflectkotlinpoet

Kotlin Reflection: How to know if a Kotlin class is marked with "internal" visibility modifier


I'm autogenerating code with KotlinPoet and Auto Service. I didn't find any way to know if an annotated class has "internal" modifier so I can create another class with same modifier. For example:

@MyAnnotation
internal class Car

So I thought using Kotlin Reflection I would be able to get this information but no luck.

With the annotator processor I'm able to get the KClass but the visibility said "public": enter image description here

Any clues on how to do it?


Solution

  • Kotlin reflection is not applicable during annotation processing. Kotlin reflection is for inspecting your code at runtime. However there is a way to parse the metadata out of Kotlin class files, it's called kotlinx-metadata-jvm.

    To use this in your annotation processor, you'll have to obtain the AnnotationMirror of the kotlin.Metadata annotation. From that mirror, obtain the annotation values and use them to construct the KotlinClassHeader as you can see in the examples for kotlinx-metadata-jvm. Once you are there you can use kotlinx-metadata-jvm to extract the flags for your class.