I have a val prop:KMutableProperty1<<A,Any>>
of field x in class A, I can get field name by prop.name
but how do I get its container class name (A)?
Accessing the declaring class is tricky because properties can have different implementing details depending on how they are defined. By using both the potential backing field as well as the public getter we can create a pretty robust way to access the declaring class:
fun KProperty<*>.declaringClass(): Class<*> {
return (this.javaField as Member? ?: this.javaGetter)?.declaringClass
?: error("Unable to access declaring class")
}
If the item is a backed property, the field will define the class it is declared in. Otherwise it will take the class declaring the getter.