0

Let's suppose I have an instance of a class X with a method Y of which we will know the name only at runtime, how can I get a reference to it using reflection?

Something like:

class X{

  fun Y(){
    
  }

}

I want to able to store the method Y in a variable and call it when needed.

I tried with X::class.java::getMethod('Y').kotlinFunction but then I will need to have an instance of such method to be able to call it, so it doesn't make any sense

1
  • You mean you want a reference to a function that is bound to a specific instance of X? Commented Jan 19, 2021 at 14:28

1 Answer 1

1

first, you need to find the function looping through class members, then call it with the required instance. if a function needs other arguments you need to pass it in order, but the first arg always needs to be the instance

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

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

Performance:

I ran the following code and got the following results:

    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
Sign up to request clarification or add additional context in comments.

9 Comments

How slow is this way compared to a direct reference like X::Y?
If you don't want to deal with nullables and know your method exists, you could call first instead of find.
@Todd if you have other members first does not work
Not if you use the lambda version - .first { it.name == "y" }.
Btw, I just tested the code and I get a type mismatched exception. The method call() is expecting a X.Y instance, not an X instance
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.