1

I'm trying to invoke a method via reflection by passing the method's invocation arguments in an array. Params is a List [Any] and carries the values to be passed to the reflected method.

// make absolutely sure it's of the correct type
val args : Array [Object] = params.map (_.asInstanceOf [java.lang.Object]).toArray
System.err.println ("target method: " + method.getName + " :: " + method.getParameterTypes.toList)
System.err.println ("parameters   : " + args.getClass.getCanonicalName + "\n    " + 
    (args map (p => (p.getClass.getCanonicalName, p))).toList)
method.invoke (host, args)

I get the following output, which all looks good. The signature of the method being invoked matches the parameter list perfectly.

target method: echo :: List(class java.lang.String)
parameters   : java.lang.Object[]
    List((java.lang.String,looks good))

Sadly, the invoke throws java.lang.IllegalArgumentException: argument type mismatch

According to the Java docs a varargs argument (as the params to Method.invoke are) can be supplied with an Object[]. I'm stumped!

1 Answer 1

6

Vararg methods can be called from scala with the :_* syntax, which tells Scala to unpack the sequence into individual arguments:

method.invoke(host, args: _*)

Here's a complete example:

class A {
  def meth(a: String, b: String) = a + b
}
val host = (new A)
val method = host.getClass.getDeclaredMethods.head
val params: List[Object] = List("a", "b")
val result = method.invoke(host, params: _*)
println(result) // ab
Sign up to request clarification or add additional context in comments.

1 Comment

Outstanding. params : _ * is exactly the piece of arcane syntax I was looking for. Thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.