3

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?

Fawfulcopter
  • 381
  • 1
  • 7
  • 15

1 Answers1

5

You need to add the spread operator * to your call:

fooMethod.invoke(fooClass, *arguments)

Using arguments without prefixing it with * will cause a new array of length 1 containing arguments as its single element to be created and passed as args to invoke. Prefixing it with the spread operator causes the arguments array to be passed to invoke as args.

See Variable number of arguments (Varargs) - Functions - Kotlin Programming Language for more details.

mfulton26
  • 29,956
  • 6
  • 64
  • 88
  • 1
    I feel like an idiot now because I remember this operator existing but it completely slipped my mind. Sometimes a guy just needs a little push. Thank you. – Fawfulcopter Mar 20 '17 at 18:26