2
votes

I want to invoke function with list parameters, this is the code:

class A {
  def cat(s1: String, s2: String) = s1 + " " + s2
}
val a = new A
val mylist = Array("hello","guys")
val argtypes = mylist.map(_.getClass)
val method = a.getClass.getMethod("cat",argtypes: _*)
method.invoke(a,argtypes: _*)

but I get errors:

java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606)

How can i do it?

1

1 Answers

3
votes

The arguments to the invoke method is the object on which the method is being invoked followed the list of actual arguments to the method. In your case you were passing the class objects of the arguments instead of the actual object. So the below should work.

scala> method.invoke(a, mylist: _*)
res3: Object = hello guys