Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Reflection - Check if property has type

I want to iterate over all fields in one of my classes, filter for annotated ones and then check if the field has one specific type.
All I found was field.returnType.isSubtype(other: KType) but I don't know how to get the KType of my other class.

Here is my code so far:

target.declaredMemberProperties.forEach {
    if (it.findAnnotation<FromOwner>() != null) {
        if ( /*  it.returnType is Component <- Here I need some working check   */ ) {

            // do stuff
         } else {

            // do ther stuff
         }
    }
}
like image 883
danielspaniol Avatar asked Dec 13 '22 23:12

danielspaniol


1 Answers

There are at least two solutions here:

  • Get the KClass<*> of it.returnType using .jvmErasure, then check the subtype relationship for the KClasses:

    it.returnType.jvmErasure.isSubclassOf(Component::class)
    
  • Since Kotlin 1.1, you can construct the KType from the KClass token using .createType() (check its optional parameters: you can use them to provide nullability info, type arguments and annotations), and then check the subtype as you suggested:

    it.returnType.isSubtypeOf(Component::class.createType())
    

    Creating the type on every iteration may introduce performance issues, make sure you cache it if you need it often.

like image 99
hotkey Avatar answered Dec 30 '22 05:12

hotkey