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)?
3 Answers
I think this is going to depend on how you get this property reference, but if you do it like this:
class A(var x: Int = 0)
val prop: KMutableProperty1<A, Any> = A::x as KMutableProperty1<A, Any>
Then this chain of attempted casts can get you a KClass
instance:
val kclass = (prop as? MutablePropertyReference1)?.owner as? KClass<*>
println(kclass) // class A
Again, this won't nearly work in every case, as there are other implementations of the interfaces that these properties actually return, so the casts might fail.

- 85,752
- 11
- 221
- 226
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.

- 24,655
- 2
- 77
- 74
I had the same problem. My solution was the following. Hope it fits in general:
class Person {
var firstname = "Stacey"
}
fun main() {
// Let's take property 'firstname' (which would be x) of class 'Person' (should be A) as example. Get the corresponding KMutableProperty.
val kMutableProperty = Person::class.members.filter { it.name == Person::firstname.name }.first()
// Get the kotlin type of the parent class, the class owning the property. For that example the kotlin type of class 'Person' is returned.
val parentKClass = (kMutableProperty.parameters[0].type.classifier as KClass<out Any>)
// In addition, get the name of type
val parentKClassName = parentKClass.simpleName
}

- 58
- 1
- 6