Den Drobiazko
Den Drobiazko

Reputation: 1086

kotlin annotation processing: check if given TypeElement is from kotlin-class

I am implementing annotation processing library that generates code using java poet based on classes that have specific annotation.

To also consume classes written in kotlin I've switched to kapt instead of apt in my sample project. It works with annotated java-classes just fine. Bun kotlin-classes have a different approach with accessing class fields: getters and setters should be used.

Is there a way to determine whether given class (more specifically - not a class but a TypeElement - since this is happening prior to compilation) is java-class or is written in kotlin? Based on that I can write code that generates fields accessing or getters-used accessing.

Upvotes: 2

Views: 2100

Answers (1)

Kiskae
Kiskae

Reputation: 25573

In theory any class compiled from kotlin will be annotated with kotlin.Metadata. You can use the getAnnotation method on TypeElement to check if that annotation is present in order to verify if they were written in kotlin.

val metaDataClass = Class.forName("kotlin.Metadata").asSubclass(Annotation::class.java)
val isKotlinClass = <TypeElement>.getAnnotation(metaDataClass) != null

Version that works without having the kotlin standard library in the processing environment:

elementUtils.getAllAnnotationMirrors(typeElement).any { 
    elementUtils.getBinaryName(it.annotationType).contentEquals("kotlin.Metadata") 
}

Upvotes: 5

Related Questions