我试图在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)
}
}
}
}
答案 0 :(得分:1)
invoke
方法采用可变数量的参数而不是参数数组。它应该是这样的:
val r = method.invoke(new ReflectionTest(), "Hello", "World", "Bye")