aggaton
aggaton

Reputation: 3350

Calling method in generic class through reflection

I am attempting to setup a function taking in a generic class that in turn calls a method within that class through reflection. Below code compiles, however when I run it I get this error:

java.lang.IllegalArgumentException: Callable expects 2 arguments, but 1 were provided.

Why does Kotlin claim there should be 2 arguments, when the method only takes one? What should the arguments be?

import kotlin.reflect.full.memberFunctions


class myClass {
    fun test(d: String) : String {
        return d
    }
}

class test {

    fun <T: Any>ProcessStuff(
        d : T
    ) {
        val myClass  = d.let { it::class }

        var f3 = myClass.memberFunctions.find { it.name == "test"}!!
        println (f3.call ("Hello World"))
    }
}

fun main(args : Array<String>) {
    val c = myClass()
    val t = test()
    t.ProcessStuff(c)
}

Upvotes: 1

Views: 698

Answers (1)

tweitzel
tweitzel

Reputation: 363

You're not calling the method on an instance (first argument). It works like this:

val myClassInstance = myClass()
println(f3.call(myClassInstance, "Hello World"))

Upvotes: 5

Related Questions