lundi 20 mars 2017

Idiomatic way to invoke methods through reflection in Kotlin

I have a piece of Kotlin code that is trying to reflectively invoke a method using Java's Reflection package:

val arguments = arrayOfNulls<Any>(numberOfParams)

// Populate arguments

try {
    fooMethod.invoke(fooClass, arguments)
} catch (e: Exception) {
    // Panic
}

It keeps failing with an IllegalArgumentException of "wrong number of parameters".

I did some reading on the issue and it seems the spread operator of the invoke() method refuses to unpack Array<Any> because it's not equivalent to Object[]. I could try to use a standard Object[] from Java, but it makes me wonder, is this the only way? Is it the best way? Is there some way I can do this with Kotlin's types?

What is the most idomatic way to achieve what I want in Kotlin?





Aucun commentaire:

Enregistrer un commentaire