Hi, Is there a way to know the instance class of a...
# announcements
p
Hi, Is there a way to know the instance class of a class property dynamically? For example I have a
data class MyClass(val person: Person)
. When MyClass is instantiated, it's built with a PersonImpl as the Person is the interface.
val result = MyClass(PersonImpl())
I need to dynamically know that the person attribute is a PersonImpl. I have been trying with `result::class.declaredMemberProperties`but I can't get the PersonImpl from it. Thanks
b
How about
result.person is PersonImpl
, or using
result.person::class
?
p
That may work but I want to make it generic. I want to get the instance class the properties of a bunch of different classes
b
Oh gotcha. This seems to work:
Copy code
fun Any.hasPersonImplPropertyValue(): Boolean =
    this::class.declaredMemberProperties.any { property ->
        (property as KProperty1<Any, *>).get(this) is PersonImpl
    }

result.hasPersonImplPropertyValue() // true
(I'm not sure how to get around the hacky-feeling
as KProperty1<Any, *>
cast so there might be a better way)
p
It worked! Thank you very much
😁 1