【问题标题】:Scala: NoSuchMethodException when invoking mutable.ArrayBuffer(List,Int)Scala:调用 mutable.ArrayBuffer(List,Int)时出现 NoSuchMethodException
【发布时间】:2017-11-05 18:20:23
【问题描述】:

我想通过反射来调用(List,Int),这是我的代码:

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]]: _*)

但是method4会出现一些错误:

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

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

有解决这个问题的办法吗?

【问题讨论】:

    标签: scala scala-collections


    【解决方案1】:

    Array 是不同于 :: 类型的 List 类型。此更改应该有效

    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]]: _*)
    

    【讨论】:

    • 感谢您的快速回复。
    【解决方案2】:

    您传递的是Array[Int]

    arg1 += Array(1,2,3)
    

    test 方法,但test 方法期待arg1: scala.collection.immutable.$colon$colon[Any]

    所以把test函数改成

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

    应该也可以

    【讨论】:

    • 很高兴听到这个消息:)
    猜你喜欢
    • 2015-01-30
    • 2016-07-23
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多