2

I would like to access Kotlin's extension functions/values through reflection. I have a very simple example, but I cannot figure out what is wrong here

import kotlin.reflect.full.*

class A

fun A.ext() = 2
val A.value: Int
    get() = 2

fun main() {
    val a = A()
    val reflection = a::class

    reflection.members.joinToString(", ") { it.name }
    reflection.declaredMemberExtensionProperties.joinToString(", ") { it.name }
    reflection.memberExtensionProperties.joinToString(", ") { it.name }
    reflection.memberExtensionFunctions.joinToString(", ") { it.name }
    reflection.declaredMembers.joinToString(", ") { it.name }
}

This, of course, won't work in the Playground, because kotlin-reflect.jar is not in the classpath there.

Neither of the options produces the expected output: ext and value. What am I missing?

Victor Ermolaev
  • 721
  • 1
  • 5
  • 16
  • 1
    Extension functions are not members of the class unless they are declared within it. I would be surprised if reflection could simply list all extensions that involve that class. That would be like listing all functions that take instances of that class as a parameter. It would be an exhaustive search of all packages. – Tenfour04 Sep 09 '20 at 16:29
  • It's not quite true, see https://discuss.kotlinlang.org/t/how-do-extension-functions-work/609/3 and https://stackoverflow.com/questions/48635210/how-to-obtain-properties-or-function-declared-in-kotlin-extensions-by-java-refle, isn't it? In particular, "Extensions are visible from Java reflection as static methods in the classes they are defined in". If you look into definitions of `extensionProperties\Functions`, exactly static props/funcs must be listed. – Victor Ermolaev Sep 10 '20 at 08:10
  • 1
    "in the classes they are defined in" is the key part of that. If the extension function isn't defined inside the class, it isn't a member of that class. In Java reflection, you wouldn't look for `Arrays.fill()` in the `Object[]` class. It's a member of `Arrays`. – Tenfour04 Sep 10 '20 at 13:42
  • I followed the advice in [another post](https://stackoverflow.com/questions/48635210/how-to-obtain-properties-or-function-declared-in-kotlin-extensions-by-java-refle). It's not ideal, but it works. – Victor Ermolaev Sep 14 '20 at 09:47

0 Answers0