Reputation: 899
I need to create a function which creates a class from an arbitrary string and passes an array of parameters to a fixed method called "render". The problem is that depending on the class the "render" method may take a varying amount of arguments. Unfortunately the "render" method cannot be changed to accept varargs so I'm wondering if I can still pass the arguments as an Array?
This yields: "java.lang.IllegalArgumentException: wrong number of arguments"
Here's the code:
def perform(strClazz: String, pTypes: Array[Class[_]], params: Array[Object]) = {
val clazz = MyClassLoader.loadClass(strClazz)
val render = clazz.getDeclaredMethod("render", pTypes: _*)
// params: java.lang.IllegalArgumentException: wrong number of arguments
render.invoke(clazz, params)
}
And I call it via:
perform("MyClass",Array[Class[_]](classOf[String], classOf[String]),Array[Any]("first", "second"))
The invoked method takes two Strings as arguments so the following DOES work:
render.invoke(clazz, "first", "second")
Is it not possible to pass an Array then?
Upvotes: 0
Views: 484
Reputation: 26579
scala> class Foo { def f(s: String, i: Int): Unit = () }
defined class Foo
scala> classOf[Foo].getDeclaredMethod("f", Array(classOf[String], classOf[Int]):_*)
res0: java.lang.reflect.Method = public void Foo.f(java.lang.String,int)
Upvotes: 2