我正在尝试使用Scala反射来找到重载方法。这是我的代码
import scala.reflect.runtime.universe._
object Example {
class Something {
def printIt(s1: String,s2: String) {println(s1 + s2) }
def printIt(s: Int) { println(s) }
def printIt(s: String) {println(s) }
def printInt(i: Int) { println(i) }
def printInt(i: String) { println(i) }
}
def main(args: Array[String]): Unit = {
val r = new Something()
val mirror = runtimeMirror(getClass.getClassLoader)
val instanceMirror = mirror.reflect(r)
val symbols = mirror.typeOf[r.type].decl(TermName("printInt")).asMethod
}
}
执行代码时,出现以下异常。
Exception in thread "main" scala.ScalaReflectionException: value printInt encapsulates multiple overloaded alternatives and cannot be treated as a method. Consider invoking `<offending symbol>.asTerm.alternatives` and manually picking the required method
通过遵循异常本身给出的建议,我能够通过遍历方法的替代方法来找到重载的方法。但是有什么方法可以使用方法所采用的参数类型来查找方法?
答案 0 :(得分:1)
使用Scala反射和迭代
val m: scala.reflect.runtime.universe.MethodSymbol =
typeOf[Something].decl(TermName("printInt")).asTerm.alternatives.find(s =>
s.asMethod.paramLists.map(_.map(_.typeSignature)) == List(List(typeOf[Int]))
).get.asMethod
或使用Java反射
val m: java.lang.reflect.Method =
Class.forName("Example$Something").getMethod("printInt", classOf[Int])