meng
meng

Reputation: 53

Scala: NoSuchMethodException when invoking mutable.ArrayBuffer(List,Int)

I want to invoke(List,Int) by reflecting, it's my code:

class TagCalculation {
  def test(arg1: scala.collection.immutable.$colon$colon[Any],arg2: java.lang.Integer) = "test mix2"
}
val getTest =  new TagCalculation

val arg1 : scala.collection.mutable.ArrayBuffer[Any] = scala.collection.mutable.ArrayBuffer()
arg1 += Array(1,2,3)

arg1 += 4

val argtypes4 = arg1.map(_.getClass)
val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
method4.invoke(getTest,calcParamsArray.asInstanceOf[Seq[Object]]: _*)

but method4 would some errors:

scala> val argtypes4 = arg1.map(.getClass) argtypes4: scala.collection.mutable.ArrayBuffer[Class[]] = ArrayBuffer(class [I, class java.lang.Integer)

scala> val method4 = getTest.getClass.getMethod("test", argtypes4: _*) java.lang.NoSuchMethodException: $iwC$$iwC$TagCalculation.test([I, java.lang.Integer) at java.lang.Class.getMethod(Class.java:1678) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:35) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:40) at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.(:42)

Any idea to solve this issue?

Upvotes: 0

Views: 121

Answers (2)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

You are passing an Array[Int]

arg1 += Array(1,2,3)

to the test method but the test method is expecting arg1: scala.collection.immutable.$colon$colon[Any]

So changing the test function to

def test(arg1: Array[Int],arg2: java.lang.Integer) = "test mix2"

should work too

Upvotes: 0

Mikel San Vicente
Mikel San Vicente

Reputation: 3863

Array is a different type than :: that is of type List. This change should work

class TagCalculation {
  def test(arg1: scala.collection.immutable.$colon$colon[Any],arg2: java.lang.Integer) = "test mix2"
}
val getTest =  new TagCalculation

val arg1 : scala.collection.mutable.ArrayBuffer[Any] = scala.collection.mutable.ArrayBuffer()
arg1 += List(1,2,3)

arg1 += 4

val argtypes4 = arg1.map(_.getClass)
val method4 = getTest.getClass.getMethod("test", argtypes4: _*)
method4.invoke(getTest,calcParamsArray.asInstanceOf[Seq[Object]]: _*)

Upvotes: 2

Related Questions