如何在 Kotlin 中使用反射获取函数引用

How to get a function reference using reflection in Kotlin

假设我有一个 class X 的实例,它的方法 Y 我们只会在运行时知道它的名称,我如何使用反射获取对它的引用?

类似于:

class X{

  fun Y(){
    
  }

}

我希望能够将方法 Y 存储在一个变量中,并在需要时调用它。

我试过 X::class.java::getMethod('Y').kotlinFunction 但是我需要有一个这样的方法的实例才能调用它,所以它没有任何意义

首先,您需要找到循环遍历 class 个成员的函数,然后用所需的实例调用它。如果函数需要其他参数,则需要按顺序传递它,但第一个参数始终需要是实例

class X {
    fun y() { println("I got called") }
}

fun main() {
    val x = X()
    x::class.members.find { it.name == "y" }
        ?.call(x)
}

性能:

我运行下面的代码得到了下面的结果:

    var start = System.nanoTime()
    val y = x::class.members.find { it.name == "y" }
    y?.call(x)
    var stop = System.nanoTime()
    println(stop - start)
    println()

    start = System.nanoTime()
    y?.call(x)
    stop = System.nanoTime()
    println(stop - start)
    println()


    start = System.nanoTime()
    x.y()
    stop = System.nanoTime()
    println(stop - start)
    println()



I got called
381566500 // with loop and reflection

I got called
28000 // reflection call

I got called
12100 // direct call