使用 getDeclaredMethod 使用函数作为参数类型

Dav*_*ola 5 java reflection kotlin

我有一个私有方法,其标题是:

private fun setNumericListener(editText: EditText, onValueChanged:(newValue: Double?) -> Unit)
Run Code Online (Sandbox Code Playgroud)

我这样调用这个方法: setNumericListener(amountEditText, this::onAmountChanged)

我想使用类 https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredMethod(java.lang.String,%20java.lang.Class.. .)获取对我的私有方法的引用setNumericListenergetDeclaredMethod接收一个参数类型数组,Class<?>... parameterTypes但是当我的私有方法将方法引用作为参数时,我不知道如何设置参数类型数组。

谢谢

Rob*_*sen 5

函数引用被解析为类型kotlin.jvm.functions.Function1

这意味着您可以getDeclaredMethod()通过调用来获取方法引用:

getDeclaredMethod("setNumericListener", EditText::class.java, Function1::class.java)
Run Code Online (Sandbox Code Playgroud)

这是一个完整的片段:

fun main(vararg args: String) {
    val method = Test::class.java.getDeclaredMethod("setNumericListener",
            EditText::class.java, Function1::class.java)

    println(method)
}

// Declarations
class Test {
    private fun setNumericListener(editText: EditText,
            onValueChanged: (d: Double?) -> Unit) {}
}

class EditText {}
Run Code Online (Sandbox Code Playgroud)

哪个打印:

getDeclaredMethod("setNumericListener", EditText::class.java, Function1::class.java)
Run Code Online (Sandbox Code Playgroud)