Retrieving a class reference from an extension function


#1

Hi Kotlin community,

Extension functions are resolved statically, and through reflection with Java I’m able to retrieve the upper class of an extension function like so. So if I place an extension function in a file called TestExtension.kt I will be able to access TextExtensionKt.class in Java. Is there a way to access this class in Kotlin too?

I’m trying to use reflection for some unit test purposes (finding ways to mock static/extension functions) but in order to do this I need a reference to the enclosing class.

Thanks in advance!

Kind regards,

Tim


#2

Let’s assume you have a package “a” with a file “Foo.kt”. I think you can do something like

val clazz = Class.forName("a.FooKt")

val m = clazz.getDeclaredMethod(....)

I found this here. Next time you might want to do some more searching using google. “kotlin reflection top level” did the trick for me.


#3

Thanks. This would probably work, although it is less than ideal because I have to include the entire package name. Thanks anyway! Believe me when I say I did google a lot (been at it the entire afternoon), just didn’t get to this phrasing I guess. Thanks again :slight_smile:


#4

Oh I do. I’m pretty sure I spent countless hours doing this myself :wink: But IMO it helps people to know what phrases lead to results. Maybe it’ll help you to find your answer the next time. If not I’ll just have to google again for you :stuck_out_tongue_closed_eyes: