Reputation: 2338
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
}
}
}
Upvotes: 4
Views: 5790
Reputation: 148169
There are at least two solutions here:
Get the KClass<*>
of it.returnType
using .jvmErasure
, then check the subtype relationship for the KClass
es:
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.
Upvotes: 14