Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use getDeclaredMethod using a function as a parameterType

I have a private method which header is:

private fun setNumericListener(editText: EditText, onValueChanged:(newValue: Double?) -> Unit)

I call this method in this way: setNumericListener(amountEditText, this::onAmountChanged)

I would like to use getDeclaredMethod from Class https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredMethod(java.lang.String,%20java.lang.Class...) to get a reference to my private method setNumericListener. getDeclaredMethodreceives an array of parameter types Class<?>... parameterTypes but I have no idea about how to set the parameter types array when my private method has a method reference as a parameter.

Thanks

like image 867
DavidGSola Avatar asked Sep 10 '18 06:09

DavidGSola


1 Answers

The function reference is resolved as being of type kotlin.jvm.functions.Function1.

This means you can use getDeclaredMethod() to get a method reference by calling:

getDeclaredMethod("setNumericListener", EditText::class.java, Function1::class.java)

Here's a complete snippet:

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 {}

Which prints:

private final void Test.setNumericListener(EditText,kotlin.jvm.functions.Function1)
like image 128
Robby Cornelissen Avatar answered Nov 05 '22 07:11

Robby Cornelissen