nz_21
nz_21

Reputation: 7343

Kotlin unable to access delegated method via reflection: "java.lang.NoSuchMethodException"

I'm trying to understand how reflection with works with delegation and I've come up with a toy example.


class Foo(val m: MutableList<Any>) : MutableList<Any> by m{
}



fun fooAdd(f: Foo) {
    val a = f::class.java.getMethod("add").invoke(f, 20);
    println(a)
}

fun main(args: Array<String>) {
    fooAdd(Foo(mutableListOf()))
}

This gives me an error:

Exception in thread "main" java.lang.NoSuchMethodException: Foo.add()

I'm not sure I understand why it's happening, seeing as add() is delegated to Foo from MutableList if I understand correctly.

How do I fix this error? Also, is there a library one ought to use for such a use-case?

Upvotes: 0

Views: 757

Answers (1)

Denis Zavedeev
Denis Zavedeev

Reputation: 8297

Class#getMethod accepts two parameters:

  1. name of a method.
  2. Parameter types (vararg of Class<?>es).

MutableList has no add method without parameters so you're getting java.lang.NoSuchMethodException.

You meant to get method like this:

clazz.java.getMethod("add", Any::class.java)

Full listing:

fun main() {
    val list = mutableListOf<Int>()
    val clazz = MutableList::class
    val method = clazz.java.getMethod("add", Any::class.java)
    method.invoke(list, 10)
    println(list)
}

Output:

[10]

Upvotes: 5

Related Questions