Getting Kotlin Class From Annotation

I wanna get KClass instance or at least the full kotlin class name that is inside a parameter in my annotation
by my annotation processor, Look at below code for more clarification

// Another developer’s code using my library
@MyAnn(kClass = List::class)

// My annotation processor code
val myAnn = element.getAnnotation(MyAnn::class.java)

myAnn.kClass // ERROR -> throws MirroredTypeException

As seen above an exception is thrown which kinda expected since that’s what said in
documentation here getAnnotation()

So to get the full name I use below code

val typeMirror = try {
myAnn.kClass as TypeMirror // won’t even reach as TypeMirror but just for type inference
}catch (e: MirroredTypeException) {
e.typeMirror
}

val typeElement = processingEnvironment.typeUtils.asElement(typeMirror) as TypeElement
// Then to get full name use below line
typeElement.qualifiedName // Done

But above approach has a problem
Which is if the class in the annotation’s parameter corresponds to a java class
Ex. @MyAnn(kClass = Boolean::class)

it returns the full name as java.lang.Boolean not kotlin.Boolean
and same thing for a lot of other classes such as List, Set etc…

I wanna get the full name of the declared class in kotlin so how to do so.

Also If there is no way what is the best workaround
I thought of 2 solutions in case above requirement is not possible to be achieved

  1. the current workaround which I use which is converting classes to kotlin by using this function JavaToKotlinClassMap which I found suggested
    in an issue in kotlinpoet (it’s the same problem) here
    BUT the same discussion it’s said it’s not accurate here
    & here as well,
    and since the second link mentioned kotlin metadata might be the approach for the solution
    I tried to ask here
    But then the reply says the question isn’t relevant to kotlinx-metadata-jvm

  2. Generated code is in java instead of in kotlin, but it’s problem is I wanna
    have extension functions so I will need the classes in kotlin so the same
    problem all over again.

Sorry for all the links, but I just wanted to show all my trials so that
no one will waste time in something that’s already have been checked

And Thanks in advance :smiley:.

1 Like

If I understand your question correctly this may help.

Unfortunately, the problem persists even if retention is set to Runtime and even with using the same code suggested in the StackOverflow post, the code still throws MirroredTypeException with typeMirror as java.lang.Boolean.

Thanks for your effort, But the problem still exists.