vendredi 3 mai 2019

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?





Aucun commentaire:

Enregistrer un commentaire