Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Kotlin中的反射获取函数引用_Kotlin_Reflection - Fatal编程技术网

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

如何使用Kotlin中的反射获取函数引用,kotlin,reflection,Kotlin,Reflection,假设我有一个类X的实例,其中有一个方法Y,我们只能在运行时知道它的名称,如何使用反射获取对它的引用 比如: class X{ fun Y(){ } } 我希望能够将方法Y存储在变量中,并在需要时调用它 我尝试了X::class.java::getMethod('Y').kotlinFunction,但是我需要有这样一个方法的实例才能调用它,所以它没有任何意义首先,您需要找到通过类成员循环的函数,然后用所需的实例调用它。如果函数需要其他参数,则需要按顺序传递,但第一个参数始

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

比如:

class X{

  fun Y(){
    
  }

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


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

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

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

你的意思是你想要一个绑定到某个特定X实例的函数的引用?与直接引用(如X::Y)相比,这种方式有多慢?如果你不想处理null值,并且知道你的方法存在,如果有其他成员,可以调用
first
而不是
find
@Todd
first
不起作用如果使用lambda版本-
。first{it.name==“y”}
。顺便说一句,我刚刚测试了代码,得到了一个类型不匹配的异常。方法调用()需要的是X.Y实例,而不是X实例