代码之家  ›  专栏  ›  技术社区  ›  bumblebee

使用scala反射查找重载方法

  •  0
  • bumblebee  · 技术社区  · 6 年前

    我正在尝试使用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
    

    通过遵循异常本身给出的建议,我可以通过迭代方法替换来找到重载的方法。但是,是否有任何方法可以使用该方法采用的参数类型来查找该方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Dmytro Mitin    6 年前

    使用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])