Is there any Scala feature that allows you to call a method whose name is stored in a string?

后端 未结 4 1372
刺人心
刺人心 2020-12-05 03:20

Assuming you have a string containing the name of a method, an object that supports that method and some arguments, is there some language feature that allows you to call th

4条回答
  •  执念已碎
    2020-12-05 03:26

    Yes you can! You would need .invoke() method of the method object. Simple example below:

     import scala.util.Try
    
     case class MyCaseClass(i: String) {
     def sayHi = {
         println(i)
       }
     }
     val hiObj = MyCaseClass("hi")
     val mtdName = "sayHi"
     // Method itself as an object
     val mtd = hiObj.getClass.getMethod(mtdName)
     Try {mtd.invoke(hiObj)}.recover { case _ => ()}
    

    see code here: https://scastie.scala-lang.org/vasily802/WRsRpgSoSayhHBeAvogieg/9

提交回复
热议问题