Scala:错误的参数数量在调用方法时出现异常

时间:2014-02-26 04:47:41

标签: scala reflection methods invoke

我试图在Scala中反射性地调用一个方法。但我仍然遇到错误数量的参数异常,即使参数看起来与方法签名匹配。

class ReflectionTest {

def myConcat (s1:String, s2:String, s3:String): String = {
return s1 + s2 + s3
}

@Test
def testReflectiveConcat = {
val s = myConcat ("Hello", "World", "Now")


val methods = new ReflectionTest ().getClass().getDeclaredMethods
for (method <- methods) {
  if (method.getName().startsWith("myConcat")) {
    // this throws IllegalArgumentException: wrong number of arguments
    val r = method.invoke(new ReflectionTest(), Array("Hello", "World", "Bye"))
    println (r)

   }
  }
 }
}

1 个答案:

答案 0 :(得分:1)

invoke方法采用可变数量的参数而不是参数数组。它应该是这样的:

val r = method.invoke(new ReflectionTest(), "Hello", "World", "Bye")