0

I am trying to find the overloaded method using Scala reflections. Here's my code

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

  }
}

When I execute the code I am getting the following exception.

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

By following the suggestion given by the exception itself, I am able to find the overloaded method by iterating through method alternatives. But is there any way of finding the method using the argument types that the method takes?

bumblebee
  • 1,811
  • 12
  • 19

1 Answers1

3

Either using Scala reflection and iterating

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

or using Java reflection

val m: java.lang.reflect.Method = 
  Class.forName("Example$Something").getMethod("printInt", classOf[Int])
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66