Get enclosing class from KProperty1


How come KProperty1<T, R> doesn’t have an extension for getting the enclosing class? I tried to define my own, but since it is an inline function, I cannot use it without breaking the existing code base.

Basically, I want something like this:

inline fun <reified T : Any> KProperty1<T, *>.getEnclosingClass(): KClass<T> = T::class

But when I call it on instance of KProperty1<T, *> in my code, I get “cannot use T as reified type parameter. Use a class instead.”


What are you trying to do? The only thing I can imagine is that you want to get the enclosing class from a delegate property. In that case you probably want to look at [provideDelegate]( that allows you to override the delegate creation. This can even be an inline extension function. This function could be used to provide the delegate with a reference to (the class of) the owner.


I want to search for an annotation of the class given its property.

I actually solved my problem by “going-to-Java-and-back-to-Kotlin way”:

val annotation = KProperty1<*, *>.javaField?.declaringClass?.kotlin?.findAnnotation<MyAnnotation>()


You don’t need to go back to Kotlin to get the annotations. They are accessible straight from the Java class object.


I know, I just really like the convenience of findAnnotation() extension function.
Or you are implying that the way I described above carries some performance penalties in comparison to Java-only way?


It requires the annotation library. If you don’t have it already it’s probably overkill to require it for this feature, especially since getAnnotation(class) works perfectly correctly.