vendredi 22 octobre 2021

Obtain KClass<*> property from Annotation using Kotlin Reflection

I have an annotation

// declaration 
annotation class MyAnnotation(val name: String, val type: KClass<*>)

// usage
@MyAnnotation(name = "name", type = String::class)
fun someFuncion()

What I'm trying to achieve is to obtain properties of my annotation using reflection (done in Annotation Processor)

So far I have managed to get the name property using this extension:

private inline fun <reified T> Any.fieldByName(name: String): T {
    try {
        return this::class.members.find { it.name == name }?.call(this) as T
    } catch (e: Exception) {
        throw IllegalArgumentException("Error process $name member: ${e.stackTraceToString()}")
    }
}

But when it comes process the type parameter I get java.lang.reflect.InvocationTargetException

What I hope to get is an instance of KClass<*> so I can do some logic later on, depending on the type.

Is there even a way to achieve that? Or why is there this error and how should I handle that scenario.

I also tried

  • javaClass.kotlin.memberProperties - same result

Thanks in Advance





Aucun commentaire:

Enregistrer un commentaire